简体   繁体   English

尝试在 Java 中的 while 循环内捕获

[英]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.当变量 digit <= 0 时,循环将继续。 if try catch an error then the digit will be set to 0 to enter the loop again.如果尝试捕获错误,则该数字将设置为 0 以再次进入循环。 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.使用 Scanner,当引发 InputMismatchException 时,Scanner 不会转到下一个令牌,因为它让我们有机会处理该令牌。

In your case, you need to invalidate the token.在您的情况下,您需要使令牌无效。 To do that you can simply use nextLine inside the catch block:为此,您只需在 catch 块中使用 nextLine :

s.nextLine();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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