简体   繁体   English

循环执行…不确定性

[英]Looping do…while uncertainty

In the catch block, I'm trying to correct for user bad-input issues. 在catch块中,我试图纠正用户输入错误的问题。 When testing it, if I use the "break" keyword, it doesn't jump to the initial question. 测试它时,如果我使用“ break”关键字,它不会跳到最初的问题。 If I use "continue", it loops infinitely. 如果我使用“ continue”,它会无限循环。 "Sc.next();" “ Sc.next();” doesn't seem to resolve it either. 似乎也无法解决。

Here's the relevant part of the code. 这是代码的相关部分。

public class ComputerAge {
    private static int age;
    private static int year;
    private static int month;
    private static int date;
    private static Calendar birthdate;

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.print("Enter the numeral representing your birth month: ");
        do {
            try {
                month = sc.nextInt();
            } catch (InputMismatchException ime){
                System.out.println("Your respone must be a whole number");
                break;
            }
        } while (!sc.hasNextInt());

The problem with your approach is that when you call sc.nextInt() and it throws an exception, Scanner does not advance its reading position. 你的方法的问题是,当你调用sc.nextInt()它抛出一个异常, Scanner不能保证它的读取位置。 You need to advance the reading pointer by calling sc.next() inside the catch block instead of the break : 您需要通过在catch块内而不是break调用sc.next()来提高读取指针:

do {
    try {
        month = sc.nextInt();
    } catch (InputMismatchException ime){
        System.out.println("Your respone must be a whole number");
        sc.next(); // This will advance the reading position
    }
} while (!sc.hasNextInt());

In order to fix the problem, we should identify what we want to accomplish at the end. 为了解决问题,我们应该确定最终要完成的工作。
We want the month to be a numeral month, that is number > 0. 我们希望月份为数字月份,即数字> 0。

Thus: 从而:

  • If a user fill a correct number month will be filled. 如果用户填写正确的数字,则将填写month
  • Otherwise, Exception will be thrown and month will stay as '0'. 否则,将引发异常,并且month将保持为“ 0”。

Conclusion: We want our program will keep running when month is equals 0. 结论:我们希望程序在month等于0时继续运行。

The solution is pretty simple: 解决方案非常简单:

While condition should be: 条件应为:

while (month == 0);

And you should change break to sc.next() . 并且您应该将break更改为sc.next()

I think you should use an infinite loop, and when the input is correct (no exception thrown), use break to finish the loop: 我认为您应该使用无限循环,当输入正确时(不引发异常),请使用break结束循环:

public static void main(String args[])
{
    System.out.print("Enter the numeral representing your birth month: ");
    do {
        try {
            int month = sc.nextInt();
            break;
        } catch (InputMismatchException ime) {
            System.out.println("Your respone must be a whole number");
            sc.nextLine();
        }
    } while (true);
}

Also, you will have to use sc.nextLine() in the catch block because when you enter some input and press Enter , a new-line character is added, and nextInt() doesn't read it. 同样,您必须在catch块中使用sc.nextLine() ,因为当您输入一些输入并按Enter时 ,将添加一个换行符,而nextInt()不会读取它。 You have to use nextLine() to consume that character. 您必须使用nextLine()消耗该字符。 For further information about this issue you could read this . 有关此问题的更多信息, 您可以阅读此内容

First of all, you have to avoid use try/catch in iteratives sentences in order to improve perfomance. 首先,您必须避免在迭代语句中使用try / catch,以提高性能。

You can recode for the break to work in this way (keep in mind that de do-while will execute at least one time, so if your scanner retrieve null value, you will have nullPointer) 您可以重新编码以使中断以这种方式工作(请记住,de-while将至少执行一次,因此,如果扫描仪检索空值,则将具有nullPointer)

    try {
       while (sc != null && !sc.hasNextInt()) {
            month = sc.nextInt();
        } 
    } catch (InputMismatchException ime){
            System.out.println("Your respone must be a whole number");
    }

Make sure you can get the integer first, and use regular expressions. 确保可以先获取整数,然后使用正则表达式。 Don't use exceptions if possible to enforce code logic. 如果可能,请不要使用异常来强制执行代码逻辑。

int month;
boolean correct = false;
while (!correct && sc.hasNextLine())
{
    String line = sc.nextLine();
    if (!line.matches("^[0-9]+$"))
    {
        System.out.println("Your response must be a whole number");
        correct = false;
    }
    else
    {
        month = Integer.parseInt(line);
        correct = true;
    }
}

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

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