简体   繁体   中英

Do/While Loop looping when condition set to false

This do/while loop will loop infinitely if it gets an error, even though error is set to false after each loop... I'm not sure how else to explain it.

import java.util.Scanner;

public class ErrorChecking {

    public static int inputInt(Scanner input, String console) {

        int finalInt = 0;
        int num;
        boolean error = false;

        do {
            error = false;
            System.out.print(console);
            if(input.hasNextInt()) {
                num = input.nextInt();
                String numDuplicate = Integer.toString(num);
                int numLength = numDuplicate.length();
                if(numLength == 8) {
                    finalInt = num;
                    error = false;
                } else {
                    System.out.println("Invalid input. ID needs to be 8 digits long. Please try again.");
                    error = true;
                }
            } else {
                System.out.println("Invalid input. ID needs to be 8 numbers. Please try again.");
                error = true;
            }
        } while(error);

        return finalInt;

    }

}

If input.hasNextInt() ever returns false , then your loop is going to run forever because you do nothing to advance the input and it will return false on every iteration. My guess (without more details about your program's behavior) is that this is what's going on.

You need to somehow consume the current input to clear the error condition. The logic for doing this depends on what you're expecting as input.

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