user2795095
user2795095

Reputation: 511

If-else statement does not work inside a while loop

I have a while loop, with an if statement inside. The if statement works fine, until I add an else statement. The problem is that when running the program, it jumps directly to the else statement, even when the condition inside the if statement is fulfilled. I can't seem to find the problem, and were hoping someone could help me...

Part of my code:

while(!filen.endOfFile()) {
    linje = filen.inLine();
    splitt = linje.split(",");  

    if (linje.toUpperCase().contains(fugl.toUpperCase())) {
        System.out.println(splitt[0] + ": ");
        System.out.println(splitt[1]);
        System.out.println(splitt[2]);
        System.out.println(splitt[3]);

    } else {
        System.out.println("Write something here..."); 
    }
}

EDIT: I tried to put the if statement as true, and now it shows the result, but the else statement is added at the bottom. I do not understand why this happens?

Upvotes: 0

Views: 7153

Answers (4)

donmj
donmj

Reputation: 409

to avoid the else statement in printing always. You must delete the else statement. Only add another else if if there is another criteria you wanna search.

Upvotes: 0

Parth Bhagat
Parth Bhagat

Reputation: 509

You can try something like this.

if (true) {
   System.out.println("Condition Satisfied");
} else {
   System.out.println("Condition not Satisfied");
}

If you have compiled the class properly then it will execute "Condition Satisfied" message on console every time.

Upvotes: 0

Parth Bhagat
Parth Bhagat

Reputation: 509

There is no reason for JVM to go for executing else block even when the if condition is satisfied. Unless the condition result returns false value or the code is not compiled properly.

So try compiling the class & try again. Though it is not working as intended then put a absolute value "true" in the if condition, compile the class & check whether it executes if block or not.

Upvotes: 0

Avi
Avi

Reputation: 21760

Usually when it happens it's because the source is not in-sync with the binaries. Try cleaning your project, and rebuild it for your IDE. Or maybe you can delete it from the IDE and import again.

Upvotes: 1

Related Questions