1. Write a Java program InputTester.java that: Prompts the user to enter “int”,
ID: 670514 • Letter: 1
Question
1. Write a Java program InputTester.java that:
Prompts the user to enter “int”, “double”, or “boolean” and then scans that into a String variable choice using Scanner;
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.”
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.”
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.”
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
package mani;
import java.util.InputMismatchException;
import java.util.Scanner;
public class CashCounter{
public static void main(String args[]){
Scanner s=new Scanner(System.in);
System.out.print("Enter int,double or boolean: ");
String choice=s.next();
if(choice.equals("int")){
System.out.print("enter an int: ");
String i=s.next();
try{
int t=Integer.parseInt(i);
double t1=Double.parseDouble(i);
if(t == Math.round(t1))
{
System.out.println("valid int was entered. ");
}else{
System.out.println("valid int was not entered. ");
}
}catch(Exception e){
System.out.println("valid int was not entered. ");
}
}else if(choice.equals("double")){
try {
System.out.print("Enter double: ");
String i=s.next();
double t = Double.parseDouble(i);
System.out.println("valid double was entered. ");
} catch (InputMismatchException e) {
System.out.println("valid int was not entered e. ");
}
}else if(choice.equals("boolean")){
System.out.print("Enter an boolean: ");
boolean b=s.nextBoolean();
if(b==true||b==false){
System.out.println("valid boolean was entered.");
}else{
System.out.println("valid boolean was not entered.");
}
}else{
System.out.println("A valid type was not entered");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.