是否有可能不仅验证用户使用 hasNextInt() 输入了一个 int,而且它也是一个数字,让我们说 1 到 4 之间的后续切换条件?所以在它达到切换条件之前,我想,一,确保用户不能用随机输入破坏它,二,接收到的输入在 1 到 4 之间。现在我知道有很多方法可以解决这个问题,但我想问问大家是否有可能以这种方式(在 hasNextInt() 的 while 循环条件内)使用尽可能少的行来做到这一点?我在这里看到了 hasNextInt() 的不同实现,但仅限于确保输入的是一个 int 而不是其他任何东西。
这只是我试图传达的概念,如果理论上这样的事情是完全可能的话
while(!input.hasNextInt() && input.nextInt() < 1 && input.nextInt() > 4){...code}
/// THIS IN A SENSE IS WHAT I COME UP WITH BUT I AM TRYING TO
/// SEE IF I CAN CONDENSE THIS WITH THE CONCEPT I STATED ABOVE. I
/// DON'T WANT THIS CODE FIXED.
Scanner input = new Scanner(System.in);
int selection = 0;
while(!input.hasNextInt()) {
System.out.print("Invalid Entry! Only numbers 1 - 4");
System.out.print("Enter Selection: ");
input.next;
}
selection = input.nextInt();
boolean flag = true;
while(flag && selection > 0 && selection < 5) {
if (selection < 1 || selection > 4) {
System.out.print("Invalid Entry! Only numbers 1 - 4");
System.out.print("Enter Selection: ");
while(!input.hasNextInt()) {
System.out.print("Invalid Entry! Only numbers 1 - 4");
input.next;
System.out.print("Enter Selection: ");
}
selection = input.nextInt();
}