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
import java.util.*;
public class DoubleSqr {
public static void main(String[] args) throws java.util.InputMismatchException {
// TODO Auto-generated method stub
try
{
double n1, sqr;
Scanner sc=new Scanner(System.in);
System.out.println(\"Enter a number\");
n1=sc.nextDouble();
sqr=n1*n1;
System.out.println(\"Squire of\"+n1+\"is\"+sqr);
}
catch(java.util.InputMismatchException E)
{
System.out.println(\" Invalid Input ==>\" +E);
}
}
}
