'Break statement not taking me outside of loop java
I am solving this problem on code forces. https://codeforces.com/contest/1675/problem/B
The break
statement I have doesn't break out of the while
loop.
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?
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);
}
}
}
}
Solution 1:[1]
i think it breaks out of the inner while loop, but not the outer for loop. So the inner while loop runs multiple times.
Solution 2:[2]
Problems
Normally a 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.
Solutions
First, always debug to see if you enter your if statement.
Second, use something else as condition of your while loop. You could use a boolean and change its value to break the while condition. 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;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alexander Berlin |
Solution 2 | AtomicUs5000 |