Java Program Write a java program in which main prompts for
Java Program:
Write a java program in which main prompts for and reads in a double constant and then displays the square of the constant. If the user does not enter a double constant, your program should reprompt the user for a valid input. [Do not use hasNextDouble to determine if the inputs is invalid. Instead, catch the exception that nextDouble throws if the input is invalid.] Your program should use the prompt and error messages illustrated by the following sample session:
Enter non-negative double constant
hello
Not a double constant. Re-enter
goodbye Not a double constant. Re-enter
4
Square of 4 = 16.0
Do not use hasNextDouble to determine if the inputs is invalid. Instead, catch the exception that nextDouble throws if the input is invalid.
Solution
package doubleconstant;
import java.util.Scanner;
public class DoubleConstant {
public void readDouble(){
Scanner sc = new Scanner(System.in);
double number;
boolean flag = false;
try{
System.out.println(\"Enter non-negative double constant\");
number = sc.nextDouble();
System.out.println(\"Square of \"+number+\"=\"+(number * number));
//System.exit(1);
}
catch(Exception e){
System.out.println(\"Goodbye! not a Double constant re-enter ...\");
readDouble();
}
}
public static void main(String[] args) {
DoubleConstant dc = new DoubleConstant();
dc.readDouble();
}
}
