In: Computer Science
Create an application that checks whether an integer is an odd or even number.
Welcome to the Odd/Even Checker! Enter an integer: ten Error! Invalid integer. Try again. Enter an integer: 10.3 Error! Invalid integer. Try again. Enter an integer: 10 The number 10 is even. Continue? (y/n): Error! This entry is required. Try again. Continue? (y/n): y Enter an integer: 9 The number 9 is odd. Continue? (y/n): n
Specifications:
Create a version of the Console class presented in chapter 7 that doesn’t use static methods. Create a MyConsole class that inherits the Console class. Then, override the getString() method so it doesn’t allow the user to enter an empty string. Use an instance of the MyConsole class to get and validate the user’s entries.
SOURCE CODE:
*Please follow the comments to better understand the code.
**Please look at the Screenshot below and use this code to copy-paste.
***The code in the below screenshot is neatly
indented for better understanding.
import java.util.*;
class MyScanner
{
public static void main (String[] args)
{
System.out.println("Welcome to the
Odd/Even Checker!");
Scanner sc=new
Scanner(System.in);
while(true)
{
// ask for input
System.out.print("Enter an integer:");
String input = sc.nextLine();
try
{
int num = Integer.parseInt(input);
// even??
if(num%2==0)
System.out.println("The number "+num+" is even");
else
System.out.println("The number "+num+" is odd");
// ask for choice
System.out.print("Continue? (y/n)");
String chioce = sc.nextLine();
if(chioce.equals("n"))
break;
}
catch (NumberFormatException e)
{
// error
System.out.println("Error! Invalid integer. Try again.");
}
}
}
}
OUTPUT:
Welcome to the Odd/Even Checker!
Enter an integer:ten
Error! Invalid integer. Try again.
Enter an integer:10.5
Error! Invalid integer. Try again.
Enter an integer:10
The number 10 is even
Continue? (y/n)y
Enter an integer:9
The number 9 is odd
Continue? (y/n)y
Enter an integer:123.er
Error! Invalid integer. Try again.
Enter an integer:123.45
Error! Invalid integer. Try again.
Enter an integer:123
The number 123 is odd
Continue? (y/n)n
Error! Invalid integer. Try again.
Enter an integer:123
The number 123 is odd
Continue? (y/n)n
(PROGRAM ENDED)
============================================