Write two small static methods and use them for every line of input.
What to build
A program that finds the largest of three numbers and says whether it is even.
Requirements
- Write
static int max3(int a, int b, int c)andstatic boolean isEven(int n). - Read n, then n lines of three numbers; for each print
max M (even)ormax M (odd).
Input
Line 1: n. Then n lines of three whole numbers.
Output
n lines.
Constraints
1 ≤ n ≤ 100; |numbers| ≤ 10^9.
Example
Input:
2
3 9 4
10 2 8
Output:
max 9 (odd)
max 10 (even)
Why it works
Each method does one job and returns its answer, so main only reads, calls and prints; isEven works for negative numbers because -4 % 2 is 0 and -3 % 2 is -1, never 0.
Examples
Example 1 · Input
2 3 9 4 10 2 8
Expected output
max 9 (odd) max 10 (even)
Example 2 · Input
1 -5 -2 -9
Expected output
max -2 (even)
Hints
Hint 1
Write static int max3(int a, int b, int c) using Math.max twice.
Hint 2
A static boolean method isEven(int n) can return n % 2 == 0.
Solution
Show one correct solution (try it yourself first)
import java.util.Scanner;
public class Main {
static int max3(int a, int b, int c) {
return Math.max(a, Math.max(b, c));
}
static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 0; i < n; i++) {
int m = max3(in.nextInt(), in.nextInt(), in.nextInt());
System.out.println("max " + m + (isEven(m) ? " (even)" : " (odd)"));
}
}
}