简体   繁体   中英

try catch inside while loop in Java

I am trying to prevent users from entering a non-numeric and negative value. while variable digit is <= 0, the loop will continue. if try catch an error then the digit will be set to 0 to enter the loop again. but instead of turning back to ask the user to input a number when the user inputs a non-numeric value, it enters an infinite loop.


import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;

public class Test {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int digit = 0;
        String playerNUmber;

        while (digit <= 0) {

            System.out.println("How many digit you want to guess?");
            try {

                digit = s.nextInt();

                char[][] users = new char[digit][1];

                do {
                    System.out.println("Please enter " + digit + " digit/s numbers.");
                    playerNUmber = s.next();

                    if (playerNUmber.length() == digit) {
                        System.out.println("Player number : " + playerNUmber);

                        for (int i = 0; i < digit; i++) {
                            users[i][0] = playerNUmber.charAt(i);

                        }

                    } else {
                        System.out.println("You must enter a " + digit + " number.");
                    }

                } while (playerNUmber.length() != digit);

            } catch (Exception e) {
                System.out.println("Enter numbers only");
                digit = 0;
            }
        }
    }
}

Using Scanner, when an InputMismatchException is thrown, Scanner is not going to the next token because it gives us the opportunity to handle that token.

In your case, you need to invalidate the token. To do that you can simply use nextLine inside the catch block:

s.nextLine();

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