[英]Break statement not taking me outside of loop java
我正在解決代碼部隊的這個問題。 https://codeforces.com/contest/1675/problem/B
我的break
語句沒有跳出while
循環。 當我使用這個輸入時:
它在同一情況下兩次輸出-1
一次,這表明break
語句沒有將我帶出循環?
為什么會這樣?
public class vanita {
public static void main (String[]args) {
Scanner in = new Scanner(System.in);
int cases = in.nextInt();
for (int i = 0; i < cases; i++) {
boolean test = true;
int arrLength = in.nextInt();
int arr[] = new int[arrLength];
for (int j = 0; j < arrLength; j++) {
arr[j] = in.nextInt();
}
int operations = 0;
int after;
for (int j = arrLength-1; j >= 1 ; j--){
after = arr[j-1];
while (arr[j] <= after) {
arr[j-1] = (int)Math.floor(arr[j-1]/2);
after = arr[j-1];
operations++;
if (arr[j] == 0 && arr[j-1] == 0) {
//System.out.println("current: " + arr[j]);
//System.out.println("after: " + arr[j-1]);
//System.out.println("Case " + i);
System.out.println("-1");
test = false;
break;
}
}
}
for (int s = 0; s < arrLength; s++) {
//System.out.print(arr[s] + " ");
}
//System.out.println(" ");
if (test == true) {
System.out.println(operations);
}
}
}
}
我認為它打破了內部的while循環,而不是外部的for循環。 所以內部的while循環會運行多次。
通常是break;
總是會跳出最近的循環。 如果你不能跳出你的循環,問題是你的算法或你的條件。
首先,始終調試以查看是否輸入了 if 語句。
其次,使用其他東西作為您的 while 循環的條件。 您可以使用布爾值並更改其值以打破 while 條件。 前任:
boolean hasFoundDuplicate = false;
while(!hasFoundDuplicate){
arr[j-1] = (int)Math.floor(arr[j-1]/2);
after = arr[j-1];
operations++;
if(arr[j] == 0 && arr[j-1] == 0){
hasFoundDuplicate = true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.