Java Control Flow

Find the largest of three numbers

Description: Write a method which gets three int numbers and returns the largest one. Test it with (12, 45, 30) and (7, 7, 3).

Hint:

  • Use if with &&, or call Math.max() two times.

Solution

public class Main {
    static int largest(int a, int b, int c) {
        if (a >= b && a >= c) return a;
        if (b >= c) return b;
        return c;
    }

    public static void main(String[] args) {
        System.out.println(largest(12, 45, 30));
        System.out.println(largest(7, 7, 3));
        System.out.println(Math.max(12, Math.max(45, 30)));    // shorter way
    }
}
Output

45
7
45

How it works

  • The first if checks if a is at least as big as both others.
  • If not, the winner is b or c, so one more comparison is enough.

Read Java if else.

Check if a year is a leap year

Description: Write a method isLeap(int year). A year is a leap year if it is divisible by 4, but not by 100, unless it is divisible by 400. Test 1900, 2000, 2024 and 2026.

Hint:

  • Use the remainder operator %.

Solution

public class Main {
    static boolean isLeap(int year) {
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    }

    public static void main(String[] args) {
        for (int y : new int[]{1900, 2000, 2024, 2026}) {
            System.out.println(y + " -> " + isLeap(y));
        }
        System.out.println(java.time.Year.isLeap(2024));       // the library method
    }
}
Output

1900 -> false
2000 -> true
2024 -> true
2026 -> false
true

How it works

  • 1900 is divisible by 100 but not by 400, so it is not a leap year. 2000 is divisible by 400, so it is.
  • Java has this check ready: Year.isLeap().

Read Java Operators.

FizzBuzz in Java

Description: Print the numbers from 1 to 15. For multiples of 3 print Fizz, for multiples of 5 print Buzz, and for multiples of both print FizzBuzz.

Hint:

  • Check the multiples of 15 (both) first.

Solution

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 15; i++) {
            if (i % 15 == 0) {
                System.out.println("FizzBuzz");
            } else if (i % 3 == 0) {
                System.out.println("Fizz");
            } else if (i % 5 == 0) {
                System.out.println("Buzz");
            } else {
                System.out.println(i);
            }
        }
    }
}
Output

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

How it works

  • If you check 3 first, then 15 would print only Fizz. So the most special case must come first.

Read Java for Loop.

Sum of the digits of a number

Description: Write a method which returns the sum of the digits of a positive number. For 9475 the answer is 25.

Hint:

  • n % 10 is the last digit, n / 10 removes it.

Solution

public class Main {
    static int digitSum(int n) {
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(digitSum(9475));
        System.out.println(digitSum(100));
        System.out.println(digitSum(0));
    }
}
Output

25
1
0

How it works

  • The loop takes the last digit, adds it, and removes it, until the number becomes 0.

Read Java while Loop.

Print a multiplication table

Description: Print the table of 7 from 1 to 10 in the format 7 x 3 = 21.

Hint:

  • A for loop from 1 to 10 and printf.

Solution

public class Main {
    public static void main(String[] args) {
        int n = 7;
        for (int i = 1; i <= 10; i++) {
            System.out.printf("%d x %2d = %2d%n", n, i, n * i);
        }
    }
}
Output

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

How it works

  • %2d uses at least 2 places, so the numbers line up in columns.

Read Java for Loop.

Check if a number is prime

Description: Write isPrime(int n). A prime number is bigger than 1 and has no divisor except 1 and itself. Print all the primes up to 30.

Hint:

  • You only need to test divisors up to the square root of n.

Solution

public class Main {
    static boolean isPrime(int n) {
        if (n < 2) return false;
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        for (int n = 1; n <= 30; n++) {
            if (isPrime(n)) System.out.print(n + " ");
        }
        System.out.println();
    }
}
Output

2 3 5 7 11 13 17 19 23 29

How it works

  • If n has a divisor bigger than its square root, it must also have a smaller one, so testing up to i * i <= n is enough.
  • The method returns false as soon as it finds a divisor.

Read Java Methods.