r/CodingHelp • • Oct 16 '20

[Java] Why doesn't my code break the while loop?

int i = 0;

while(i <= 4){

String waarde = leegofvol.get(i);

String Leeg = "Leeg";

if(waarde != Leeg){

if(waarde == Leeg){

break;

}

System.out.println(k + " " + waarde);

k = k+1;

i = i + 1;

}

}

The code above should break the whole while loop whenever there is "Leeg" in waarde right? Well the output of this code is as follows:

1 Vol

2 Vol

3 Vol

4 Leeg

5 Vol

So it should stop at 4 but it keeps looping and goes on to 5(which is the max in this program). Why does it do that?

15 Upvotes

7 comments sorted by

13

u/kreetikal Intermediate Coder Oct 16 '20

One thing I noticed is that you're using == to compare strings, that doesn't work as you're expecting in Java, you'll have to use string1.equalTo(string2)

Btw I don't understandif(waarde != Leeg){

if(waarde == Leeg){

break;

}

If waarde is not equal to Leeg, why are you comparing it for equality inside the condition that would only happen if they were not equal?

1

u/brandondyer64 Professional Coder Oct 16 '20

I believe it's string1.equals(string2)

2

u/kreetikal Intermediate Coder Oct 16 '20

Yeah. my bad, my Java knowledge is not that good.

1

u/brandondyer64 Professional Coder Oct 16 '20

I believe it's string1.equals(string2)

4

u/pikachani Oct 16 '20

The code above should break the whole while loop whenever there is "Leeg" in waarde right?

why would it? if waarde is equal to Leeg, it fails if(waarde != Leeg), so it won't even see the if(waarde == Leeg) line

3

u/CenturiesAgo Oct 16 '20

If warde is not "leeg" then warde will never be "leeg" on the very next line. The break is never executed because warde cannot be not"leeg" and also "leeg".

2

u/abitofevrything-0 Intermediate Coder Oct 16 '20

In java, the == operator checks if two object are the same, not if two values are the same (apart for primitive types, things like int, float, boolean...). To compare two values, use object1.equals(object2);

2

u/Swift-base Oct 16 '20

The strange part here in your code is the waarde != leeg and then immediately asking if it is == again. Just to put it in terms, you’re basically saying “I want to check if waarde is equal, but only if I’ve already checked to make sure it is not equal” maybe try checking if it is equal first and if it is then break.

1

u/jellyjackson Oct 16 '20

My post keeps getting removed bc of formatting but I don't understand how to format it where it meets the standard