Arithmetic in java
I have the following homework problem:
开发者_如何学GoWrite an application integer on that reads an integer and determines and prints whether it is odd or even.
Use the Scanner class for reading input.
Store that input into an integer. Check if input is really a valid integer. Otherwise, throw an exception.
Afterwards, use the modulo operator to check if it's odd or even.
Use System.out.println to print if it's odd or even.
public static void main(String[] args) {
System.out.println("Enter number");
Scanner sc = new Scanner(System.in);
try {
int i = sc.nextInt();
if (Math.abs(i) / i == 1) {
if ((Math.abs(i) % 2) == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
}
} catch (Exception ex) {
System.out.println("Exception " + ex.toString());
}
}
精彩评论