Saturday, October 4, 2014

if-else. How to not execute both statements.


Hi, I am making a program, where the user answers 3 questions and then I add the number of correct answers in to the (int) numberofcorrect variable, then I want to print the results, and no matter how many correct, the program executes first the correct if statement, then the else statement.

Eg: I have 2 correct it will print:

"Grade B, 2 of 3 "

"You failed the test"


Why does it do that? How can I change my code so the else statement dosent print if one of the if statments is allready printed?

I want to know how to not execute the else statement, if one of the if statements have allready been executed.


Below is my current code for this problem:


if (numberofcorrect == 3){

System.out.println("Grade A, full score");}

if (numberofcorrect == 2){

System.out.println("Grade B, 2 of 3 ");}

if (numberofcorrect ==1) {

System.out.println("Grade C, 1 of 3");}

else {

System.out.println("You failed the test"); }



No comments:

Post a Comment