如何循环用户输入,直到输入整数? [英] How to loop user input until an integer is inputted?

查看:155
本文介绍了如何循环用户输入,直到输入整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,我想继续要求用户输入,直到用户输入一个整数,所以没有InputMismatchException。我已经尝试过这个代码,但是当我输入一个非整数值时,我仍然会得到异常。

I'm new to Java and I wanted to keep on asking for user input until the user enters an integer, so that there's no InputMismatchException. I've tried this code, but I still get the exception when I enter a non-integer value.

int getInt(String prompt){
        System.out.print(prompt);
        Scanner sc = new Scanner(System.in);
        while(!sc.hasNextInt()){
            System.out.println("Enter a whole number.");
            sc.nextInt();
        }
        return sc.nextInt();
}

感谢您的时间!

推荐答案

使用Juned的代码,我可以缩短。

Working on Juned's code, I was able to make it shorter.

int getInt(String prompt) {
    System.out.print(prompt);
    while(true){
        try {
            return Integer.parseInt(new Scanner(System.in).next());
        } catch(NumberFormatException ne) {
            System.out.print("That's not a whole number.\n"+prompt);
        }
    }
}

这篇关于如何循环用户输入,直到输入整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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