简体   繁体   中英

How to fix loop while/try catch error in java

I am working on creating a simple calculator program (first week into this java programming).

problem background: only 5 options are valid. (1-add; 2- subtract; 3- multiple;4. divide; and 5.exit). when users enter 1-4 options, results will populate but users need to loop back to reenter data till option 5 is selected. 5 is to exit the program(the only way to end the loop/program). my questions: 1. how to stop try-catch from running nonstop? is there a better way to implement try-catch? eg, handling string data error messages.Ideally, if a string is entered, the code should loop back to restart again by producing the message "please reenter the number..." until a valid number is entered by users 2. I am trying to use as many static methods as possible in the main class. i am not sure whether the way I did was accurate?

Here is the code I input:

    12 2 
    //-everything works well.
    2 //-enter again 
    s s (string entry-error) 

then, the below message populates:

    "You have entered invalid floats. please re-enter:  
    Exception in thread "main" java.util.InputMismatchException
        ...
        at calculator.performSubtract(calculator.java:65)
        at calculator.main(calculator.java:34)" 

code(sample)

   public class calculator {
//use static methods to implement the program 
    static Scanner userInput = new Scanner(System.in);
    static int userChoice;
    static float numberOne;
    static float numberTwo; 
    static float answer; 
    static int choice;

    public static void main(String[] args) {
       do {
       //this menu statement has to be repeated unless 5 is entered (exit the 
      //program) 
        System.out.println("Welcome to <dj's> Handy Calculator\n\n\t \1. Addition \n\t 2. Subtraction\n\t 3. Multiplication\n\t 4. Division\n\t 5. Exit\n\n");
        System.out.print("What would you like to do? ");

        try {   
        choice = userInput.nextInt();
        }catch (InputMismatchException e) {
            continue;
        }
        switch (choice) {
        case 2: performSubtract();
        break;
        ...
        case 5: exit();
        break;
        } 
        }while(choice >0 && choice <5);
        userInput.close();
    }

    public static void performSubtract () {
        //catch error statement. 
        try {
        numberOne = userInput.nextFloat();
        numberTwo= userInput.nextFloat();
        answer= numberOne-numberTwo;
        } catch (Exception e) {
        System.out.println("You have entered invalid floats. please re-enter:  ");
        numberOne = userInput.nextFloat();
        numberTwo= userInput.nextFloat();
        }
        System.out.printf("Please enter two floats to subtraction, separated by a space: %.1f %.1f\n", numberOne, numberTwo);
        System.out.printf("Result of subtraction %.1f and %.1f is %.1f\n", numberOne, numberOne, answer);
        System.out.println("\nPress enter key to continue...");
    }

}

I believe the issue is that you are not clearing the problem token from the scanner. Your catch statement prints an error message, and then goes around to try and parse the same token into an int or float again.

You might check here: https://www.geeksforgeeks.org/scanner-nextint-method-in-java-with-examples/

It looks like you need to call userInput.next() to advance past the invalid token.

Also, hasNextInt() will let you avoid the catch altogether if you prefer.

To the first question: try-catch block are usually used to see if your code are running through without error. By what you explain what you are trying to do, I would instead use a while-loop before the assignment for numberOne and numberTwo whether the input was float or not like:

// pseudo

while(input != float || input2 != float)
{
  print(please reenter)
}
numberOne = input
numberTwo = input2

Your error lies in the fact that Scanner.nextFloat , when reading an invalid input, does not advance the current token. This means that when you call nextFloat twice again in the catch statement, you once again read the tokens s and s , the first of which will cause an InputMismatchException to be thrown once again. You should change your performSubtract method to look something like this:

public static void performSubtract () {
    //catch errors
    System.out.println("Please enter two floats to subtraction, separated by a space");
    userInput.nextLine();//ignore the new line
    do {
        try {
            String[] nextLineTokens = userInput.nextLine().split("\\s+");
            if(nextLineTokens.length != 2)
            {
                System.out.println("You have not entered two floats. please re-enter:");
                continue;
            }
            numberOne = Float.parseFloat(nextLineTokens[0]);
            numberTwo = Float.parseFloat(nextLineTokens[1]);
            answer= numberOne-numberTwo;
            break;
        }
        catch (Exception e) {
            System.out.println("You have entered invalid floats. please re-enter:  ");
        }
    } while (true);
    System.out.printf("You entered: %.1f %.1f\n", numberOne, numberTwo);
    System.out.printf("Result of subtraction %.1f minus %.1f is %.1f\n", numberOne, numberTwo, answer);
    System.out.println("\nPress enter key to continue...");
    userInput.nextLine();
}

Additionally, your parsing code continues if you enter an invalid input, but exits if you type in a number that is not 1-5. If it is the first time that you read in input, the code exits for invalid inputs as well. You should probably change your parse iteration loop as so:

public static void main(String[] args) {
    while(choice != 5) {
        //this menu statement has to be repeated unless 5 is entered (exit the 
        //program) 
        System.out.println("Welcome to <dj's> Handy Calculator\n\n\t 1. Addition \n\t 2. Subtraction\n\t 3. Multiplication\n\t 4. Division\n\t 5. Exit\n\n");
        System.out.print("What would you like to do? ");

        try {   
            choice = userInput.nextInt();
        }
        catch (InputMismatchException e) {
            userInput.next();
            continue;
        }
        switch (choice) {
            case 2: performSubtract();
            break;
            // ...
            case 5: exit();
            break;
        } 
    }
    userInput.close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM