Ask the user to enter a number Then tell the user whether th
Ask the user to enter a number. Then tell the user whether the number is positive or negative and whether the number is even or odd. (Note that 0 is considered to be even and positive.) Your program should also make sure that valid input has been entered.
After your program has processed a single number, it should ask the user if he wants to try another number. If the user answers yes (y), your program should repeat. If the user answers no (n) your program should end.
Solution
NumberEntry.java
import java.util.Scanner;
public class NumberEntry {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
char ch = \'\\0\';
while(ch != \'n\' && ch !=\'N\'){
System.out.print(\"Enter a number: \");
int n = scan.nextInt();
if(n>=0){
System.out.print(\"Given number is positive\");
}
else{
System.out.print(\"Given number is negative\");
}
if(n % 2 == 0){
System.out.println(\" and even\");
}
else{
System.out.println(\" and odd\");
}
System.out.print(\"Do you want to trye another number (y/n): \");
ch = scan.next().charAt(0);
}
}
}
Output:
Enter a number: 6
Given number is positive and even
Do you want to trye another number (y/n): y
Enter a number: -6
Given number is negative and even
Do you want to trye another number (y/n): y
Enter a number: 5
Given number is positive and odd
Do you want to trye another number (y/n): y
Enter a number: -5
Given number is negative and odd
Do you want to trye another number (y/n): n
