Try and Catch InputMismatchException: Error Checking Integer - Logic Incorrect

73 views Asked by At

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;
1

There are 1 answers

0
Mohammed Julfikar Ali Mahbub On

What you need is a recursion when InputMismatchException is thrown instead of keyboard.nextLine(); //nextLine for a reason. Moreover, you do not need to pass the value in the argument/ parameter of promptErrorCheckingPercent() 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-language that supports Pointer (address of the variable) but for the sake of security it is not allowed in JAVA.

You can look into the code below to check if it can solve your problem.

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter the name:");
        String sName = keyboard.nextLine();
        System.out.print("Please enter the percent achieved for " + sName + ": %");
        int iPercent = promptErrorCheckingPercent();
    }
    
    public static int promptErrorCheckingPercent() {
        Scanner keyboard = new Scanner(System.in);
        boolean valid = false;
        int test = -1;
        while (!valid) {
            try {
                test = keyboard.nextInt();
                valid = true;
            } catch(InputMismatchException e) {
                System.out.println("Invalid Input. Please enter a valid integer");
                return promptErrorCheckingPercent(); // Recursion by calling the method itself
            }
        }   
        return test;
    }
}