DEV Community

Hanna
Hanna

Posted on

#08, It's Not That Hard~ Conditionals and Loops (Chapter 04, Sec 01, 02)

  • Textbook: Self-Study Java (by Shin Yong-kwon)
  • Sections: Chapter 04 Sec 01, Sec 02, Chapter Review Exercises
  • Study Period: 2026-03-17 (Wed) ~ 2026-03-18 (Thu)

Before starting Chapter 4, I was really worried because it looked so difficult. But after reading through it a few times, I think I've grasped the concepts. (Grasping the concepts doesn't necessarily mean I'm good at coding yet... ^^)


1. Conditionals: if & switch

if Statements

  • Conditionals use expressions that result in true or false, or boolean type variables.
  • If the condition is true, the code inside the brackets executes. If false, it doesn't.
  • Things to watch out for: At first, I didn't understand the expression and used a regular arithmetic expression instead of one that returns true/false... Also, you shouldn't put a ; after the condition; you need to open a curly bracket {!
  • I also learned about else if. If the if statement is false, it moves to the else if part. You can use multiple else if blocks.

Math.random() Method

  • A cool method that picks a double type random number between 0.0 and 1.0.
  • It's a bit tedious if you want to use it as an integer.
  • Example (Rolling a die): int num = (int)(Math.random() * 6) + 1;

switch Statements

  • The execution is determined by a variable value rather than a true/false condition.
  • It looks much cleaner when handling multiple cases, which I like.
  • Caution: You must use break; to exit the condition! If you forget it, all subsequent statements will execute until a break; is found. (Mistake alert!)

2. Loops: for & while

Conditionals were okay, but loops were harder to understand. On the bright side, once you get it, the code becomes much simpler.

  • Variable Declaration: If you want to use a variable outside the loop's brackets, you must declare it outside before the loop starts.
  • Exiting Nested Loops: You can use break inside a loop. If you want to exit the outer loop from within a nested one, you can label the outer loop and use break LabelName;.

3. Chapter 4 Exercise Solutions

Q. Chapter 04_sec02 : Page 161, Question 3 (Rolling dice until the sum is 5)

My Code (Incorrect)

int n = (int)(Math.random()*6) + 1;
int m = (int)(Math.random()*6) + 1;

while (m + n != 5) {
    System.out.println("(" + m +","+ n+")");
    if (m + n == 5) {
        break;
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Why it's wrong: If you declare the random numbers outside the while loop, it doesn't pick new numbers inside. (It just printed the same numbers forever lol). Also, it didn't print the case where m + n == 5 and just stopped randomly.
  • Lesson: To pick a new number when it's not the target, both the random method and the print method must be inside the while loop!

Textbook Answer

while (true) {
    int num1 = (int)(Math.random()*6) + 1;
    int num2 = (int)(Math.random()*6) + 1;
    System.out.println("("+ num1 + ", " + num2 + ")");
    if((num1 + num2) == 5) {
        break;
    }
}
Enter fullscreen mode Exit fullscreen mode

AI's Refined Code (Using while condition)

int n = 0; 
int m = 0;

while (m + n != 5) {
    n = (int)(Math.random() * 6) + 1; 
    m = (int)(Math.random() * 6) + 1;
    System.out.println("(" + m + "," + n + ")");
}
Enter fullscreen mode Exit fullscreen mode
  • I have a habit of declaring everything outside, but the AI used the while (m + n != 5) condition directly to make it cleaner without an extra if or break.

AI's Do-While Version

int n, m; 

do {
    n = (int)(Math.random() * 6) + 1; // 1. Roll first
    m = (int)(Math.random() * 6) + 1;
    System.out.println("(" + m + "," + n + ")"); // 2. Print first
} while (m + n != 5); // 3. Then check if the sum is 5 to decide whether to repeat
Enter fullscreen mode Exit fullscreen mode
  • The do-while loop executes at least once. However, in practice, the while loop is used more often because it's safer to check the condition first.

Q. Chapter 04_sec02 : Page 161, Question 4 (Solving 4x + 5y = 60)

My Code (Incorrect)

int x = 0;
int y = 0;

for (x=1;x<=10;x++) {
    for (y=1; y<=10;y++) {
        (4*x) + (5*y) == 60; // Just calculating, doing nothing
    }
    System.out.println("(" + x + "," + y + ")"); // Print is outside the inner loop
}
Enter fullscreen mode Exit fullscreen mode
  • Why it's wrong: Since the print statement was outside the nested for loop, it only printed when y reached 11. I should have used an if statement to control the output. I need to make sure I don't let the print statement "escape" the brackets!

Textbook Answer

for (int x = 1; x <= 10; x++) {
    for (int y = 1; y <= 10; y++) {
        if ((4*x + 5*y) == 60) {
            System.out.println("(" + x + "," + y + ")");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Q. Chapter 04_sec02 : Page 161, Questions 5 & 6 (Star Patterns)

  • Q5: Stars increasing from the left.
  • Q6: Stars increasing from the right.
  • These were so hard I didn't even know where to start... It's amazing that you can do this with nested for loops.

Answer for Q5

for (int i = 1; i < 5; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print("*");
        if (j == i) {
            System.out.println();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Answer for Q6

for (int i = 1; i < 5; i++) {
    for (int j = 4; j > 0; j--) {
        if ( i < j ) {
            System.out.print(" ");
        } else {
            System.out.print("*");
        }
    }
    System.out.println();
}
Enter fullscreen mode Exit fullscreen mode

I feel like coding is for people who are good at math or love puzzles. It fits those who like everything to fall perfectly into place according to rules. The problem is, I don't think I'm that kind of person lol. They say "just coders" won't be needed in the AI era, but I'm just starting... am I going to be one of those developers who get weeded out? ^^...


4. Chapter 04_sec02 : Page 162, Question 7 (Bank Account Program)

import java.util.Scanner;

public class Exercise07 {
    public static void main(String[] args) {
        // 1. Declare outside the loop (To maintain data and control state)
        boolean run = true; 
        int balance = 0; 

        Scanner scanner = new Scanner(System.in);

        while (run) {
            System.out.println("-------------------------------------");
            System.out.println("1.Deposit | 2.Withdraw | 3.Balance | 4.Exit");
            System.out.println("-------------------------------------");
            System.out.print("Selection> ");

            int menuNum = scanner.nextInt();

            switch (menuNum) {
                case 1:
                    System.out.print("Deposit amount> ");
                    balance += scanner.nextInt(); // Add to existing balance
                    break;
                case 2:
                    System.out.print("Withdrawal amount> ");
                    balance -= scanner.nextInt(); // Subtract from existing balance
                    break;
                case 3:
                    System.out.print("Balance> ");
                    System.out.println(balance); // Print current balance
                    break;
                case 4:
                    run = false; // 2. Changing this to false stops the while loop on the next check!
                    break;
            }
            System.out.println();
        }

        System.out.println("Program terminated");
    }
}
Enter fullscreen mode Exit fullscreen mode

Realizations on Variable Placement

  • Why declare run and balance outside?
    • The run variable: If declared inside the while loop, it resets to true every time the loop repeats. Even if you set it to false in case 4, it becomes true again on the next turn, leading to an infinite loop!
    • The run = false approach: While break only exits the switch statement, changing the run variable controls the while loop itself, which feels much safer!
    • The balance variable: We don't want it to reset to 0 every time the loop repeats! To keep the data, it must be declared outside. Also, I used compound assignment operators because I'm "accumulating" values rather than just assigning them.
  • Variable Lifecycle: I must remember that putting int balance = 0; inside the while loop would cause a disaster where the balance resets to 0 every time I press a button... ^^

Summary: If data needs to be remembered, declare it outside the loop. If it should start fresh every time, declare it inside the loop!


Man, I spent all day on these exercise explanations... Tomorrow is the "Reference" section, and they say it's even harder than conditionals/loops. I'm in trouble...

Would you like me to translate this into a different tone, or help you prepare for the next section on References?

Top comments (0)