Write a Java program InputTester.java that: i. Prompts the user to enter “int”,
ID: 3664660 • Letter: W
Question
Write a Java program InputTester.java that:
i. Prompts the user to enter “int”, “double”, or “boolean” and then scans that into a String variable choice using Scanner;
ii. If “int” is entered, prompts the user to enter an int, then checks to make sure that the user actually has input a valid int value, and reports at the command line to the user whether or not what they entered was valid – e.g., if a valid int was entered, print “A valid int was entered.” or if a valid int was not entered, print “A valid int was not entered.”
iii. If “double” is entered, prompts the user to enter a double, then checks to make sure that the user actually has input a valid double value, and reports at the command line to the user whether or not what they entered was valid – e.g., if a valid double was entered, print “A valid double was entered.” or if a valid double was not entered, print “A valid double was not entered.”
iv. If “boolean” is entered, prompts the user to enter a boolean, then checks to make sure that the user actually has input a valid boolean value, and reports at the command line to the user whether or not what they entered was valid – e.g., if a valid boolean was entered, print “A valid boolean was entered.” or if a valid boolean was not entered, print “A valid boolean was not entered.”
v. If one of these 3 valid types (“int”, “double”, or “boolean”) was not entered in step i, then print at the command line that “A valid type was not entered.”
Explanation / Answer
Answer -
import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter type: ");
s = in.nextLine();
System.out.println("You selected type of input : "+s);
if(s.equalsIgnoreCase("int"))
{
int a;
System.out.println("Enter an integer :");
a = in.nextInt();
try
{
IOException e = new IOException();
if (a==(int)a)
{
System.out.println("A valid int was entered.");
}
else
{
System.out.println("A valid int was not entered");
throw e;
}
}
catch( IOException ioe)
{
}
}
else if(s.equalsIgnoreCase("double"))
{
double a;
System.out.println("Enter an Double :");
a = in.nextDouble();
if (a==(double)a)
{
System.out.println("A valid double was entered.");
}
else
{
System.out.println("A valid double was not entered");
}
}
else if(s.equalsIgnoreCase("boolean"))
{
boolean a;
System.out.println("Enter an boolean");
a = in.nextBoolean();
if (a==(boolean)a)
{
System.out.println("A valid boolean was entered.");
}
else
{
System.out.println("A valid boolean was not entered");
}
}
else
{
System.out.println("A valid type was not entered");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.