[英]Break statement not taking me outside of loop java
I am solving this problem on code forces.我正在解决代码部队的这个问题。 https://codeforces.com/contest/1675/problem/B
https://codeforces.com/contest/1675/problem/B
The break
statement I have doesn't break out of the while
loop.我的
break
语句没有跳出while
循环。 When I use this input:当我使用这个输入时:
It outputs -1
one twice in the same case, which shows that the break
statement isn't taking me outside the loop?它在同一情况下两次输出
-1
一次,这表明break
语句没有将我带出循环?
Why is this happening?为什么会这样?
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);
}
}
}
}
i think it breaks out of the inner while loop, but not the outer for loop.我认为它打破了内部的while循环,而不是外部的for循环。 So the inner while loop runs multiple times.
所以内部的while循环会运行多次。
Normally a break;
通常是
break;
will always break out of the most recent loop.总是会跳出最近的循环。 If you can't break out of your loop, the problem is your algorithm or your condition.
如果你不能跳出你的循环,问题是你的算法或你的条件。
First, always debug to see if you enter your if statement.首先,始终调试以查看是否输入了 if 语句。
Second, use something else as condition of your while loop.其次,使用其他东西作为您的 while 循环的条件。 You could use a boolean and change its value to break the while condition.
您可以使用布尔值并更改其值以打破 while 条件。 Ex:
前任:
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.