Reputation: 47
I am new to Java and really kind of teaching myself. I am practising with the else and if statement. I have written the below very basic program for grading a score but i cannot get all of the else if statements to work properly, it invokes the first two and i can get it to display the A and B grades but not the rest, i have tried moving and removing the squiggly brackets and such but still wont work. Please help and excuse my ignorance as i am new to Java programming.
Thanks in advance.
public class Grade {
public static void main(String[] arguments) {
int grade = 69;
if (grade > 90) {
System.out.println("Well done you got a A");
} else if (grade < 90) {
System.out.println("Well done you got a B");
} else if (grade < 85) {
System.out.println("You got a C");
} else if (grade < 75) {
System.out.println("You got a D");
} else if (grade < 75) {
System.out.println("You got a E");
} else {
System.out.println("You got a F");
}
}
}
Upvotes: 1
Views: 5115
Reputation: 7919
In case of 69 if (grade < 90)
is true so it will not execute other if
below it
Instead do
if (grade >= 90) {
System.out.println("Well done you got a A");
} else if (grade >= 85) {
System.out.println("Well done you got a B");
} else if (grade >= 75) {
System.out.println("You got a C");
} else {
System.out.println("You got a D");
}
and to add more grades add more else if(){}
to above also remember to put else{}
condition at the last so if no option is true that else will be executed.
Also check Java Docs
Upvotes: 3
Reputation: 3275
change your code to this:
public class Grade {
public static void main(String[] arguments) {
int grade = 69;
if (grade >= 90) {
System.out.println("Well done you got a A");
} else if (grade >= 85) {
System.out.println("Well done you got a B");
} else if (grade >= 75) {
System.out.println("You got a C");
} else if (grade >= 65) {
System.out.println("You got a D");
} else if (grade >= 55) {
System.out.println("You got a E");
} else {
System.out.println("You got a F");
}
}
}
because 69 IS smaller than 90 so the second if will be true and the guy will get a B although he should have a D. If the first if fails (which means grade is lower than 90, then you check if the grade is greater or equal to 85 (then get B), orelse check if it is greater or equal than 75 et cetera
Upvotes: 1
Reputation: 563
If you enter 0 as marks, it will satisfy the first else if condition, that is, 0 < 90, from there, it will not bother to check the other else if statements. Try starting from the lower marks first or write it like that to be sure:
if (grade>85 && grade<90)
System.out.Print("Grade here");
Upvotes: 0
Reputation: 49
The comparision signs are wrong. It will always fall into the first or second if. You must always test to be higher, not lower
Upvotes: 1