此代码检查用户输入的内容是否有效.如果不是数字,它将继续循环直到收到数字.之后,它将检查该数字是否在界限内或小于界限.它将继续循环直到收到入站号码.但是我的问题是,当我打印选择项时,它仅显示插入的最后一个数字之后的前一个数字.为什么会这样呢?
public void askForDifficulty(){
System.out.println("Difficulty For This Question:\n1)Easy\n2)Medium\n3)Hard\nChoice: ");
int choice = 0;
boolean notValid = true;
boolean notInbound = true;
do{
while(!input.hasNextInt()){
System.out.println("Numbers Only!");
System.out.print("Try again: ");
input.nextLine();
}
notValid = false;
choice = input.nextInt();
}while(notValid);
do{
while(input.nextInt() > diff.length){
System.out.println("Out of bounds");
input.nextLine();
}
choice = input.nextInt();
notInbound = false;
}while(notInbound);
System.out.println(choice);
}
最佳答案
这是因为while条件中的input.nextInt()使用了整数,因此它后面的那个读取了下一个.编辑您还需要组合两个循环,如下所示:
int choice = 0;
for (;;) {
while(!input.hasNextInt()) {
System.out.println("Numbers Only!");
System.out.print("Try again: ");
input.nextLine();
}
choice = input.nextInt();
if (choice <= diff.length) break;
System.out.println("Out of bounds");
}
System.out.println(choice);