扫描仪对象不返回预期结果

时间:2015-05-11 04:14:06

标签: java java.util.scanner

我正在尝试使用scanner对象来验证一些用户输入。根据我的要求,如果用户输入 100>输入< 0 ,我需要提供一些控制台输出。但是,当我输入100/0并为我提供一些空的控制台输出时,以下代码不起作用。我尝试使用102和-1测试此代码块,并使用相同(空)控制台输出

public int validateScore(Scanner sc) {
        int score = 0;
        System.out.println("Please Enter Student's Score.");
        for (;;) {
            if (!sc.hasNextInt()) {
                System.out.println("Please enter the score and in number");
                sc.next(); // discard
            }else if (sc.nextInt() > 100){
                sc.next(); // discard
                System.out.println("Please enter the score and in number in between 0-100 only: ");                
            }else if (sc.nextInt() < 0){
                sc.next(); // discard
                System.out.println("Please enter the score and in number in between 0-100 only: ");                
            }else {
                score = sc.nextInt();
                break;
            }
        }
        return score;
    }

2 个答案:

答案 0 :(得分:4)

由于在if else块中使用了nextInt(),导致错误。使用方法hasNextInt()并在验证值之前将值存储在临时变量中。

答案 1 :(得分:2)

您不应多次阅读Scanner。只需通过nextInt将数字读入变量并检查即可。否则,在每个if分支上,系统将提示您输入新号码。

public int validateScore(Scanner sc) {
    int score = 0;
    System.out.println("Please Enter Student's Score.");
    for (;;) {
        if (!sc.hasNextInt()) {
            System.out.println("Please enter the score and in number");
            sc.next(); // discard
        } else {
            int nextInt = sc.nextInt();
            if (nextInt > 100) {
                System.out.println("Please enter the score and in number in between 0-100 only: ");
            } else if (nextInt < 0) {
                System.out.println("Please enter the score and in number in between 0-100 only: ");
            } else {
                score = nextInt;
                break;
            }
        }
    }
    return score;
}