again:
while (!s.hasNextInt()) s.next();
amount = s.nextInt();
if(amount < 0 || amount > numberOfCards) {
System.out.println("You need to enter a number between 0 and "+numberOfCards);
goto again;
}
它在C#中运行良好,但在Java中没有goto。我可以想到大量复杂的重做方法,但我对编写此代码最干净最推荐的方法感兴趣。
答案 0 :(得分:1)
愚蠢的方式:
while (true) {
while (!s.hasNextInt()) s.next();
amount = s.nextInt();
if(amount < 0 || amount > numberOfCards) {
System.out.println("You need to enter a number between 0 and "+numberOfCards);
} else {
break;
}
}
答案 1 :(得分:0)
将它包裹在一个循环中:
while (amount < 0 || amount > numberOfCards) {
while (!s.hasNextInt()) s.next();
amount = s.nextInt();
if(amount < 0 || amount > numberOfCards) {
System.out.println("You need to enter a number between 0 and "+numberOfCards);
}
}