Im trying to create a code where I read a double and print out its square, but I also want it to know when the user enters a negative or non double constant and make them enter a new number. Im having trouble with the InputMismatchException. My code does not work properly, it compiles but the compiler just runs forever. Any suggestions would be helpful.
import java.util.*;
class constants
{
public static void main(String[] args)
{
double constant = getConstant();
System.out.println("Square of " + constant + " = " + constant*constant);
}
//-------------------------------------------------------------------------------
public static double getConstant()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter non-negative double constant");
double constant = kb.nextDouble();
try {
double selection = kb.nextDouble();
}
catch (InputMismatchException e) // where there is error.
{
System.out.println("Not a double constant. Re-enter");
}
return constant;
}
}