java如何在循环中重复进程
我正在编写代码,让用户猜测数字。他们只有两次机会获得全部 如果用户输入错误(超过1-4), 他们可以再做一次在这种情况下,用户必须回答2和4才能获得全部强>
System.out.println("you have only two chance to get all");
int guessnum[] = new int[2];;
for (int i = 0; i < guessnum.length; i++) {
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
}
else {
System.out.println("number must be 1-4 only, try again");
//how to repeat in same loop
}
}
# 1 楼答案
使用
break
语句# 2 楼答案
这是我所有的代码,在两个机会,用户需要把2和4赢
# 3 楼答案
你可以试试这个
# 4 楼答案
# 5 楼答案
如果要使用
for
循环,可以在System.out.println("number must be 1-3 only, try again");
之后的最后一个else
块中编写类似的--i;
代码因此,此代码将解决您的问题:
更新
在我上面的回答中,我刚刚说过,如何在对原始代码进行最小更改的情况下重复
for
循环。正如标题中所问的那样。但是@JayPrakash说这不是一个完美的答案,所以投票否决了它。好的,让我们试着找到一个完美的: