验证扫描仪的输入:它是一个整数并且在一定的数字范围内?

时间:2016-01-20 18:19:30

标签: java java.util.scanner

我是编程新手,我目前正在学习Java课程,我必须验证用户的扫描仪输入。下面的代码似乎有效,但我认为它有点效率低下。必须有更好的方法来做到这一点!

欢迎您的建议!

以下是我所拥有的:

do {
    System.out.println("What is you age?");
    while (!scSudoku.hasNextInt()) {
        System.out.println("You must enter an number");
        scSudoku.next();
    }
    age = scSudoku.nextInt();
    if (age < 10 || age > 90) {
        System.out.println("You age must be within 10 and 90");
    }
} while (age < 10 || age > 90);

2 个答案:

答案 0 :(得分:1)

使用nextLine()丢弃任何错误输入。

使用永不停止的循环防止代码重复,并breakreturn退出循环。我更喜欢在辅助方法中隔离代码并使用return

private static int promptAge(Scanner sc) {
    System.out.println("What is you age?");
    for (;;) {
        if (! sc.hasNextInt()) {
            System.out.println("You must enter an number");
        } else {
            int age = sc.nextInt();
            if (age >= 10 && age <= 90)
                return age;
            System.out.println("You age must be within 10 and 90");
        }
        sc.nextLine(); // discard (rest of) line of input
    }
}

答案 1 :(得分:0)

尝试将scSudoku.next();替换为scSudoku.nextLine。它可能运行得更顺畅,但我的Java有点生疏。 我记得使用nextLinenextln代替next而不是scSudoku.next();,而且程序也有效。

编辑: 尝试将scSudoku.nextln替换为nextln。似乎nextWhateverYou'reUsing被更广泛地使用。

编辑2: 或者只使用(defun string-or-function-p (x) (typep x '(or string function)))

相关问题