← Zurück zum Kurs: Java from scratch

Week 3 practice: games and numbers

Video folgt in Kürze

This lesson is practice. You will combine conditionals, loops and Scanner to build small but complete programs, which is the best way to turn theory into skill. We will solve three classic problems: a number guessing game, the search for prime numbers and a menu that repeats until the user decides to quit. Try to solve each one on your own before reading the solution.

Problem 1: guess the number

The program picks a secret number between 1 and 100 and the player tries to guess it; after each attempt the program says whether the number is higher or lower and counts the attempts. To generate the number we use the java.util.Random class: new Random().nextInt(100) + 1 gives an integer from 1 to 100. Here we pass a fixed seed (42) and a simulated Scanner so the result is always the same and you can check it; in your real version you will use new Random() and System.in. The loop is a while because we do not know how many attempts will be needed.

java
import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Random random = new Random(42);              // fixed seed for the demo
        int secret = random.nextInt(100) + 1;
        System.out.println("(secret is " + secret + ")");

        Scanner in = new Scanner("50 25 10 " + secret);  // simulated guesses
        int attempts = 0;
        int guess = 0;

        while (guess != secret) {
            guess = in.nextInt();
            attempts++;
            if (guess < secret) {
                System.out.println(guess + " is too low");
            } else if (guess > secret) {
                System.out.println(guess + " is too high");
            } else {
                System.out.println("Correct in " + attempts + " attempts!");
            }
        }
    }
}

Problem 2: prime numbers

A prime number is divisible only by 1 and by itself. To know whether n is prime it is enough to try divisors from 2 up to the square root of n: if none divides exactly, it is prime. This problem uses one for inside another, a break to leave as soon as we find a divisor and a boolean variable as a flag. It is a very common pattern: you assume something is true, try to disprove it inside the loop and at the end you look at the flag. Notice that 0 and 1 are not prime and need a separate case.

java
public class Main {
    public static void main(String[] args) {
        System.out.print("Primes up to 30: ");
        for (int n = 2; n <= 30; n++) {
            boolean isPrime = true;                  // the flag
            for (int d = 2; d * d <= n; d++) {
                if (n % d == 0) {
                    isPrime = false;
                    break;                           // no need to keep testing
                }
            }
            if (isPrime) {
                System.out.print(n + " ");
            }
        }
        System.out.println();

        // Sum of digits of a number using % 10 and / 10
        int number = 48213;
        int sum = 0;
        while (number > 0) {
            sum += number % 10;     // last digit
            number /= 10;           // remove last digit
        }
        System.out.println("Digit sum: " + sum);    // 18
    }
}

Problem 3: repeating menu

Almost every console application has a menu: options are shown, the user picks one, the program runs it and returns to the menu until quit is chosen. The ideal structure is a loop combined with a switch expression. Keep a variable with the balance or state and modify it according to the option. As always, validate the input: an unknown option must show a message and ask again, not close the program.

java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner("1\n2\n7\n3\n");  // simulated choices
        int counter = 0;
        boolean running = true;

        while (running) {
            System.out.println("1) Add  2) Reset  3) Quit");
            int option = in.nextInt();
            switch (option) {
                case 1 -> {
                    counter++;
                    System.out.println("Counter: " + counter);
                }
                case 2 -> {
                    counter = 0;
                    System.out.println("Counter reset");
                }
                case 3 -> running = false;
                default -> System.out.println("Unknown option: " + option);
            }
        }
        System.out.println("Bye");
    }
}
  • Week 3 in short: if / else if / else, ternary and the arrow switch.
  • while when you do not know the rounds, do-while to run at least once, for to count.
  • break leaves the loop, continue jumps to the next round.
  • Flag pattern: assume, disprove inside the loop, look at the result.
  • Break the problem into small steps and test with known inputs before accepting a program as finished.

Teste dein Wissen

Frage 1 von 6

Which loop guarantees the body runs at least once?

✎ Meine Notizen

Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen

← ZurückWeiter →