试图提示用户从catch块重新进入,但catch块终止了吗? [英] Trying to prompt the user to re-enter from the catch block, but the catch block terminates?

查看:197
本文介绍了试图提示用户从catch块重新进入,但catch块终止了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序,要求用户输入他们的年龄并提示他们重新输入,如果他们输入了不正确的值(例如负数,年龄超过120岁,有特殊字符或字母的年龄,超出范围的数字等......)

I am trying to write a program to ask a user to enter their age and prompt them to re-enter if they enter an improper value (such as a negative number, older than 120, an age with special characters or letters, an out of range number etc...)

我尝试写一个try / catch来要求用户重新输入他们的年龄:

I tried writing a try/catch to ask the user to re-enter their age:

System.out.println("Enter your age (a positive integer): ");
    int num;

    try {
        num = in.nextInt();
        while (num < 0 || num > 120) {
            System.out.println("Bad age. Re-enter your age (a positive integer): ");
            num = in.nextInt();
        }
    } catch (InputMismatchException e) {
        //System.out.println(e);
        System.out.println("Bad age. Re-enter your age (a positive integer): ");
        num = in.nextInt();
    }

当输入的年龄包含特殊字符/字母或超出范围时,程序DOES打印出Bad age。重新输入您的年龄(正整数),但此后会立即终止此错误:

When the age entered contains special characters/letters or is out of range, the program DOES print out the words "Bad age. Re-enter your age (a positive integer)," however it immediately terminates thereafter with this error:

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Unknown Source)
at java.base/java.util.Scanner.next(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
at Age.main(Age.java:21)

我的目标是让程序继续提示对于有效年龄,直到用户获得其权利。
我真的很感激任何反馈和帮助。我是一个java初学者:)
谢谢

My goal is to get the program to continue prompting for a valid age until the user gets its right. I would really appreciate any feedback and help. I am a java beginner :) Thank you

我试图改变将整个代码放入while循环但是它会导致无限循环...请帮忙!

I tried to change put the whole code into a while loop but then it causes an infinite loop... please help!

while (num < 0 || num > 120) {
        try {
            System.out.println("Bad age. Re-enter your age (a positive integer): ");
            num = in.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("Bad age. Re-enter your age (a positive integer): ");
        }
    }


推荐答案

自你试图捕获无效的输入状态,同时仍然提示用户输入正确的值, try-catch 应该封装在循环作为验证过程的一部分。

Since you're trying to capture an invalid input state while still prompting the user for a correct value, the try-catch should be encapsulated within the loop as part of it's validation process.

使用 nextInt 读取输入时,输入无效未删除,因此您需要确保在尝试重新读取之前清除缓冲区,使用 nextLine 。或者您可以放弃它,直接使用 nextLine 直接读取 String 值,然后将其转换为 int 使用 Integer.parseInt ,个人而言不那么麻烦。

When reading input using nextInt, invalid input is not removed, so you will need to ensure that you clear the buffer before attempting to re-read it, using nextLine. Or you could just forego it and just read the String value using nextLine directly and then convert it to an int using Integer.parseInt, which is, personally, less troublesome.

Scanner scanner = new Scanner(System.in);
int age = -1;
do {
    try {
        System.out.print("Enter ago between 0 and 250 years: ");
        String text = scanner.nextLine(); // Solves dangling new line
        age = Integer.parseInt(text);
        if (age < 0 || age > 250) {
            System.out.println("Invalid age, must be between 0 and 250");
        }
    } catch (NumberFormatException ime) {
        System.out.println("Invalid input - numbers only please");
    }
} while (age < 0 || age > 250);

使用 do-while 循环,基本上是因为,即使第一遍

The uses a do-while loop, basically because, you have to iterate at least once even for a valid value on the first pass

这篇关于试图提示用户从catch块重新进入,但catch块终止了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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