【问题标题】:Java Scanner Validation returning the second inputJava Scanner Validation 返回第二个输入
【发布时间】:2012-08-18 10:24:09
【问题描述】:

我在这里有一个函数,它可以验证用户输入是数字还是在范围内。

public static int getNumberInput(){
    Scanner input = new Scanner(System.in);
    while(!Inputs.isANumber(input)){
        System.out.println("Negative Numbers and Letters are not allowed");
        input.reset();
    }
    return input.nextInt();
}


public static int getNumberInput(int bound){
    Scanner input = new Scanner(System.in);
    int val =   getNumberInput();
    if(val > bound){
        System.out.println("Maximum Input is only up to: "+ bound+" Please Try Again: ");
        input.reset();
        getNumberInput(bound);
    }
    return val;
}

每次我用这个函数调用 getNumberInput(int bound) 方法时

public void askForDifficulty(){
    System.out.print("Difficulty For This Question:\n1)Easy\n2)Medium\n3)Hard\nChoice: ");
    int choice = Inputs.getNumberInput(diff.length);
    System.out.println(choice);
}

如果我插入了一个超出范围的数字,可以说唯一的最大数字是 5。getNumberInput(int bound) 将再次调用自己。当我插入正确的值或绑定值时,它只会返回我插入的第一个值/上一个值

【问题讨论】:

    标签: java input io java.util.scanner


    【解决方案1】:

    getNumberInput(int bound) 中的if 应该是while。 编辑您还应该结合这两种方法:

    public static int getNumberInput(int bound){
        Scanner input = new Scanner(System.in);
        for (;;) {
            if (!Inputs.isANumber(input)) {
                System.out.println("Negative Numbers and Letters are not allowed");
                input.reset();
                continue;
            }
            int val = getNumberInput();
            if (val <= bound) {
                break;
            }
            System.out.println("Maximum Input is only up to: "+ bound+" Please Try Again: ");
            input.reset();
        }
        return val;
    }
    

    【讨论】:

    • 它正在工作,但只有在我输入 2 次后才会读取输入。
    • 重置有什么作用?真的需要重置吗?
    • @user962206 我从您的代码中复制了 reset() 调用。如果您认为没有必要,请随意删除它。
    猜你喜欢
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多