I am trying to create a method for error checking input using a try and catch statement with the catch InputMismatch. It is not working can anyone advise why my return statement is not returning the input from the user and storing it in the integer which is called in the main class(call statement is not included).
System.out.print("Please enter the percent achieved for " + sName + ": %");
PromptErrorCheckingPercent(iPercent);
public static int PromptErrorCheckingPercent(int test){
Scanner keyboard = new Scanner(System.in);
boolean valid = false;
while (!valid)
{
try
{
test = keyboard.nextInt();
valid = true;
}
catch(InputMismatchException e)
{
System.out.println("Invalid Input. Please enter a valid integer");
keyboard.nextLine(); //nextLine for a reason
}
}
return test;
What you need is a recursion when
InputMismatchExceptionis thrown instead ofkeyboard.nextLine(); //nextLine for a reason. Moreover, you do not need to pass the value in the argument/ parameter ofpromptErrorCheckingPercent()method because what you are trying is not allowed in JAVA.Probably you were thinking passing that variable will help you to store the data in that variable. It is a feature of
C-languagethat supportsPointer(address of the variable) but for the sake of security it is not allowed inJAVA.You can look into the code below to check if it can solve your problem.