[英]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.