Java Scanner验证返回第二个输入 [英] 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;
}
每次用此函数调用getNumberInput(int bound)方法
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);
}
如果我插入一个超出范围的数字,可以说唯一的最大数字是5 .getNumberInput(int bound)将再次调用自身。当我插入正确的或在限定值内时,它只会返回我插入的第一个值/上一个值
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
推荐答案
如果
应为 getNumberInput(int bound)
中的,而
。 编辑您还应该合并这两种方法:
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;
}
这篇关于Java Scanner验证返回第二个输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!