This program takes user input and applies modulo 2 to get the remainder and then uses the result to output whether the number is even or odd.
My Code
import java.util.Scanner;
public class EvenOrOdd {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// Type your program here
System.out.println("Type a number: "); //input number
int inp = Integer.parseInt(reader.nextLine());
int rem = inp % 2; // use modulo to find remainder
// loop to output result based on remainder
if (rem == 1 || rem == -1) {
System.out.println("Number " + inp + " is odd.");
} else {
System.out.println("Number " + inp + " is even.");
}
}
}
Model Code
public class EvenOrOdd {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// Type your program here
System.out.print("Type a number: ");
int number = Integer.parseInt(reader.nextLine());
System.out.println(""); // Blank line
if (number % 2 == 0) {
System.out.println("Number " + number + " is even.");
} else {
System.out.println("Number " + number + " is odd.");
}
}
}
There are a couple of differences between my code and the model code. I introduce a variable that doesn’t really need to be there (rem) whereas the model code uses the loop to process the user input. Where I really seem to have gone wrong is by using the remainder of 1 too base my loop on. Because negative numbers also can be used I ended up with (rem == 1 || rem == -1) instead of (int % 2 == 0).