验证扫描仪的输入:是否为整数且在一定数字范围内? [英] Validate input of a scanner: is it an integer and within a certain number range?

查看:58
本文介绍了验证扫描仪的输入:是否为整数且在一定数字范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,目前正在学习Java类,在该类中必须验证用户的扫描器输入.下面的代码似乎可以正常工作,但是我认为它效率不高.必须有更好的方法来做到这一点!

I'm new at programming and I am currently following a Java class where I must validate a user's scanner input. The code below seems to work but I think it's a little bit inefficient. There must be a better way to do this!

欢迎您提出建议!

这就是我所拥有的:

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);

推荐答案

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

Use nextLine() to discard any bad input.

通过使用永无止境的循环来防止代码重复,并使用breakreturn退出循环.我更喜欢将代码隔离在辅助方法中,并使用return.

Prevent code-duplication by using a never-ending loop, and either break or return to exit the loop. I prefer isolating the code in a helper method and use 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
    }
}

这篇关于验证扫描仪的输入:是否为整数且在一定数字范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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