[英]How to use continue for a while loop in a nested for loop?
我現在正在控制台中輸入一個典型的游戲。 但是我對循環有一個錯誤。 如何在 while 循環中的 for 循環中使用 continue 關鍵字? 我想將它用於 while 循環。
*****while (true) {
System.out.print("Please type a number(It must be in between 0-"+width2+") to define the row : ");
int x = input.nextInt();
while (x<1 || x>width) {
System.out.print("Please type a avaliable number to define the row : ");
x = input.nextInt();
}
System.out.print("Please type a number(It must be in between 0-"+length2+") to define the column : ");
int y = input.nextInt();
while (y<1 || y>length) {
System.out.print("Please type a avaliable number to define the column : ");
y = input.nextInt();
}
System.out.println();
int value = 10*x + y;
for (int i = 0; i < x * y; i++) {
if (value == array[i]) {
System.out.println("Please type different values from beforehands.");
continue;
}
}
array[counter] = value;
System.out.println("array["+counter+"] = "+array[counter]);
counter++;
if (gamingArea[x-1][y-1] == 0) {
point+=10;
continue;
}else {
System.out.println("GAME OVER! Your point is "+point+".");
break;
}
}*****
您可以 label while
語句並在continue
語句中指定它。
L: while (true) {
// A
for (int i = 0; i < x * y; i++) {
if (value == array[i]) {
System.out.println("Please type different values from beforehands.");
continue L;
}
}
//
}
你也可以這樣寫而不continue
。
while (true) {
// A
if (IntStream.range(0, x * y).anyMatch(i -> i == value)) {
System.out.println("Please type different values from beforehands.");
} else {
// B
}
}
您可以簡單地刪除代碼中的第二個continue
語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.