r/javahelp • u/katiexmarkell • Sep 08 '24
Why is my code not working?
every time i run my code, there is not output for the last three if statements. what am i doing wrong?
if (credits >= 0) {
if (credits <= 29) {
System.out.print("Freshman");
}
}
else if (credits >= 30) {
if (credits <= 59) {
System.out.println("Sophmore");
}
}
else if (credits >= 60) {
if (credits <= 89) {
System.out.println("Junior");
}
}
else if (credits >= 90) {
System.out.println("Senior");
}
3
Upvotes
1
u/ChaiTRex Sep 08 '24 edited Sep 08 '24
Consider this:
If you get inside the
Acurly brace pair (the// A stuff herepart), you can't get into theBorCcurly brace pairs. Why? Because you can't get into more than one of the curly brace pairs in anif/else if/elsesetup.With your code, let's say that
creditsis 67. Your program runs theif (credits >= 0) {line. Well, 67 is greater than 0, so it goes into that curly brace pair and so it can never get down into theelse if (credits >= 60) {curly brace pair like you wanted it to because that would be going inside more than one curly brace pair in anif/else if/elsesetup, which is not allowed.How can you fix this? Well, you have the right idea. You're trying to make sure that
creditsis greater than or equal to zero AND less than or equal to 29. How do you do that properly? You use&&like this:if (credits >= 0 && credits <= 29) {.If you do it that way, then when
creditsis 67, it can't get into theif (credits >= 0 && credits <= 29) {curly brace pair anymore because&&requires it to meet both conditions, and 67 doesn't meet both conditions. So it still has a chance to get inside the correct curly brace pair because it hasn't used up its one chance to go into a curly brace pair.