r/javahelp • • Jul 03 '19

Solved Why is my If, else if statement skipping the if part?

I have an if, else if statement written in my code

If(exam.getGrade()>70) { System.out.println('P'); } else if(exam.getGrade()<70) { System.out.println('F'); }

I tried changing the code around. The numbers. Nothing worked. I can't figure out why it prints out 'F' when in the full code, the exam score is 90

0 Upvotes

13 comments sorted by

3

u/_DTR_ Jul 03 '19

What does the implementation of your getGrade() method look like? At a glance nothing seems out of place, though if the score is exactly 70 you'll skip both conditions. One of them should be >=/<=

1

u/emokii Jul 03 '19

My getGrade() method is just a list of else if statements which set a letter grade depending on the score of the exam. Now I need to have it print out if the person passed or failed. Depending on their score

3

u/_DTR_ Jul 03 '19

What does getGrade() return? I would expect the method to look something like this:

public int getGrade()
{
    return grade;
}

If it's not as simple as that, can you show us what the implementation is?

1

u/emokii Jul 03 '19

Public char getGrade() { Char letterGrade(); If(score>=90) LetterGrade = 'A'; else if(score >=80) LetterGrade = 'B';

Etc

Return letterGrade; }

How do I indent this to make it more neat, sorry

5

u/_DTR_ Jul 03 '19

If you prefix each line with (at least) 4 spaces, it will

create
a
code
block

You're returning a char, but trying to compare it to an int. getGrade() should be returning an integer. When you return A and compare it to 70, it converts the A to its underlying integer representation, which is 65. 65 is less than 70, so the if is skipped. You either need to compare getGrade to the actual letter, or change the return type of getGrade() to be an int and return score.

1

u/emokii Jul 03 '19

Thank you!

2

u/Qteddy Jul 03 '19

Your getGrade method is returning a char but you are comparing it to an int. So in your if-else statement you are basically saying if (A > 70)

1

u/emokii Jul 03 '19

I just realized this 😓

2

u/Qteddy Jul 03 '19

We’ve all been there. Helps to have another set of eyes sometimes

1

u/emokii Jul 03 '19

This can't be the problem because in all my codes recently, the if statement has been skipped.

1

u/crypt0herb Jul 03 '19

Typically else if is followed by else. Try replace elseif with else and see what happens. You can alternatively achieve the same using switch-case on exam.getGrade(). This is a pretty straight forward example of conditional logic.