1

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

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) 将再次调用自己。当我插入正确的值或在边界值内时,它只会返回我插入的第一个值/上一个值

4

1 回答 1

1

if中的应该getNumberInput(int bound)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;
}
于 2012-08-23T00:44:44.240 回答