mercredi 25 mai 2016

Java - If statement problems - changing conditions deletes the other statements bellow

newbie in a IT world with some begginers problems. So, i was going through some tutorial, and caught up a problem I cant solve by myself. The code is bellow :

    boolean gameOver = true;
    int score = 5000;
    int levelCompleted = 5;
    int bonus = 100;

        if(score == 5000)
            System.out.println("Your score is 5000");

    if(score > levelCompleted){
        System.out.println("Score is greater that levelCompleted");
        System.out.println("5000 is greater that 5");
        System.out.println("Some new text on true condition");
        }

    if(score<5000){ 
        System.out.println("Score is equal to 5000");
        }
        else
        { 
        System.out.println("Condition is false");
        }

    if((score < 5000) &&  (score > 1000)){ 
        System.out.println("Both conditions are true"); 
        }
        else if(score<1000)
        { 
        System.out.println("Else if condition is true"); 
        }
        else
        { 
        System.out.println("None of the condtitions are true!");


    if(gameOver == true){ 
        int finalScore = score + (levelCompleted * bonus);  
        System.out.println("Your final score was " + finalScore);
        }


    if(gameOver == true){
        score = 10000; 
        levelCompleted = 8;
        bonus = 200;
        int finalScore= score + (levelCompleted * bonus);
        System.out.println("Your final score was " + finalScore);
        }


    System.out.println(score);
    }

    System.out.println(levelCompleted);

    }

}

The output of the code above shows expected results and they are :

Your score is 5000
Score is greater that levelCompleted
5000 is greater that 5
Some new text on true condition
Condition is false
None of the condtitions are true!
Your final score was 5500
Your final score was 11600
10000
8

But, when I change on if/else if/else statement the if condition from

 if ( (score < 5000) &&  (score > 1000) )

to

if( (score == 5000) &&  (score > 1000) )

As you can see, i've only changed from < to == , and I get the following output.

Your score is 5000
Score is greater that levelCompleted
5000 is greater that 5
Some new text on true condition
Condition is false
Both conditions are true
5

So, what happened to the other two if-s bellow?

And where are the last two "stand-alone" system.out.println-s?

Also, where's the 5 coming from now? I suppose from levelCompleted variable, but how?

Thanks in advance for your help and explanation!

Aucun commentaire:

Enregistrer un commentaire