In: Computer Science
CODE IN JAVA
Create a new class named Task1. In its main function, use Scanner to read integers from the keyboard with the method nextInt. Use a try catch block to capture non-integer input, and tell the user, "This is not an Integer". The program loop should end when the user enters the string "quit". (Hint: "quit" is clearly not a number and will be captured in the try / catch block.)
A typical Output Dialog is shown below:
Enter an Integer: 5 You typed.......: 5 Enter an Integer: 91 You typed.......: 91 Enter an Integer: 8.7 >>> That is not an Integer! Enter an Integer: 34 You typed.......: 34 Enter an Integer: Isabelle >>> That is not an Integer! Enter an Integer: 45 You typed.......: 45 Enter an Integer: quit ::: End Program
import java.util.Scanner;
import java.util.*;
public class Task1
{
public static void main(String
[]args)
{
Scanner scan = new
Scanner(System.in);
boolean flag=true;
while(flag)
{
System.out.print("Enter an Integer:");
try
{
int n=scan.nextInt();
System.out.println("You typed........"+n+"\n");
}
catch(InputMismatchException
e) //capture error
when input dont have integer value
{
try
{
float s=scan.nextFloat();
System.out.println(">>>That is not an
Integer!"+"\n");
}
catch(InputMismatchException e2) //capture error
when input dont have float value
{
String s=scan.nextLine();
if(s.equals("quit"))
//check for end of program
{
System.out.println("::End Program"+"\n");
flag=false;
}
else
System.out.println(">>>That is not an
Integer!"+"\n");
}
}
}
}
}
output