如何保持循环并尝试以获取正确的输入? [英] How to keep looping with try and catch to get correct input?

查看:32
本文介绍了如何保持循环并尝试以获取正确的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个检查整数的函数,并将一直循环播放,直到用户正确输入17或更高的整数为止.但是,如果我输入了错误的输入(例如'K'或'&'),它将陷入无限循环.

I'm trying to make a function that checks for an integer and will keep looping until the user correctly enters an integer of 17 or higher. However, if I put in wrong input, like 'K', or '&', it will get stuck in an infinite loop.

public static int getAge(Scanner scanner) {
    int age;
    boolean repeat = true;

    while (repeat) {
        try
        {
          System.out.println("Enter the soldier's age: ");
          age = scanner.nextInt();
          repeat = false;
        }
        catch(InputMismatchException exception)
        {
          System.out.println("ERROR: You must enter an age of 17 or higher");
          repeat = true;
        }
    }
    return age;
}

推荐答案

如果下一个可用的输入令牌不是整数,则 nextInt()会将输入保持未消耗状态,并缓冲在 Scanner中.这个想法是,您可能想尝试使用其他 Scanner 方法(例如 nextDouble())读取它.不幸的是,这也意味着,除非您采取某些措施来摆脱缓冲的垃圾,否则下一次对 nextInt()的调用将只会尝试(失败)再次读取同一垃圾.

If next available input token isn't an integer, nextInt() leaves that input unconsumed, buffered inside the Scanner. The idea is that you might want to try to read it with some other Scanner method, such as nextDouble(). Unfortunately, this also means that unless you do something to get rid of the buffered-up garbage, your next call to nextInt() will will just try (and fail) to read the same junk over again.

因此,要清除垃圾,您需要先调用 next() nextLine(),然后再尝试调用 nextInt()再次.这样可以确保下次调用 nextInt()时,它将具有新数据,而不是相同的旧垃圾:

So, to flush out the junk, you need to call either next() or nextLine() before trying to call nextInt() again. This ensures that the next time you call nextInt(), it will have new data to work on instead of the same old garbage:

try {
    //...
} 
catch(InputMismatchException exception)
{
    System.out.println("ERROR: You must enter an age of 17 or higher");
    scanner.next();   // or scanner.nextLine()
    repeat = true;
}

这篇关于如何保持循环并尝试以获取正确的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆