简体   繁体   中英

Java Scanner Validation returning the second input

I have a function here where it verifies the user input if its a number or within bounds.

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

Each time I call getNumberInput(int bound) method with this function

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

if I inserted an out of bound number lets say the only maximum number is 5. the getNumberInput(int bound) will call itself again. and when I insert the correct or within bound value it will only return to me the first value/previous value I inserted

The if in the getNumberInput(int bound) should be a while . EDIT You should also combine the two methods:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM