输入错误的输入值后,要求用户再次输入输入. InputMismatchException? [英] Asking user to enter the input again after he gives a wrong value for the Input. InputMismatchException?

查看:211
本文介绍了输入错误的输入值后,要求用户再次输入输入. InputMismatchException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下用于输入用户年龄的类,然后在控制台中显示适当的信息.

I have created the following class for Inputting a user's age and then displaying appropriate info in the console.

在运行该程序时,控制台会询问请输入您的年龄:"

On running this program , the console asks "Please Enter your Age : "

如果用户输入一个整数,例如:25,则执行的类在控制台中显示"Your age is:25".

If the user enters an Integer for eg: 25 , the executed class displays " Your age is : 25" in the console.

如果用户输入非整数,则控制台将显示: 年龄应该是整数 请输入您的年龄:

If the user enters a non-integer number , the console displays: Age should be an Integer Please Enter your Age:

但是,当我将光标放在请输入您的年龄:"旁边时,我无法通过键盘输入任何内容.

But I am not able to enter anything through the keyboard when I place my cursor next to "Please Enter your Age: ".

我希望用户能够再次输入他的年龄,&如果他输入一个整数,它将显示正确的输出,但是如果他输入一个非整数,则控制台应再次询问他的年龄.

I want the user to be able to enter his age again, & if he enters an integer it displays the proper output but if he enters a non-integer the console should ask him again for the age.

如果您查看我的代码,则可以通过在主函数else块中调用checkAge()函数来设置变量'age'的值.

If you look at my code I'm setting the value of the variable 'age' by calling the function checkAge() inside the else block in my main function.

有人可以告诉我我要去哪里错吗?

Can anybody tell me where I am going wrong?

public class ExceptionHandling{

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

    public static void main(String[] args){ 
        int age = checkAge();

        if (age != 0){
            System.out.println("Your age is : " + age);         
        }else{
           System.out.println("Age should be an integer");
           age = checkAge();
        }
    }

    public static int checkAge(){
        try{            
            System.out.print("Please Enter Your Age :");
            return userinput.nextInt();
        }catch(InputMismatchException e){
            return 0;
        }
    }
}

推荐答案

如果希望执行多次(直到用户输入有效年龄),则应将代码放入循环中:

You should put your code in a loop if you wish it to execute multiple times (until the user inputs a valid age) :

public static void main(String[] args)
{
    int age = checkAge();
    while (age == 0) {
       System.out.println("Age should be an integer");
       userinput.nextLine();
       age = checkAge();
    }

    System.out.println("Your age is : " + age);
}

这篇关于输入错误的输入值后,要求用户再次输入输入. InputMismatchException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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