-4

I am using intellij & java to make a program that can calculate the users grade based on their input.So far I have successful gathered the input from the user by using scanner and got an average. I am using the average to print a letter grade by else if statements. But my program only prints out a letter grade for the grade F it doesn't print any other even when I enter scores that average to 90.

String grade;

    if (avg >= 90.0 ) {
        grade = "A";
    } else if (avg >=80.0) {
        grade = "B";
    } else if (avg >=70.0){
        grade = "C"
    } else if (avg >=60.0) {
        grade = "D";
    } else {
        grade = "F";
        System.out.println("Grade is  " + grade );
    }
}
}

I expected the program to check all else if statements but if score has an average of 60 or higher it will not print the grade is statement and will just show the average only.

azro
  • 53,056
  • 7
  • 34
  • 70
Kimiko Misaki
  • 13
  • 1
  • 5

2 Answers2

2

the problem is that your print statement is inside else block, but you do not want to print only when else, you do want to print always, should be outside of the if-else blocks.

if(A){
   ....// here you are when A is true
 } else if(B){
   .... //here you are when A is false and B is true
 } else {
   .... //here you will be when A and B are false
 }
 System.out.println("grade is:"+ grade); //here you are outside the else block so It does not depend on A nor on B value
vmrvictor
  • 683
  • 7
  • 25
1

You have to it in 2 steps, because here the print is ONLY in one case:

  1. check in which range the avg is and set the grade
  2. print the grade
if (avg >= 90.0) {
    grade = "A";
} else if (avg >= 80.0) {
    grade = "B";
} else if (avg >= 70.0) {
    grade = "C";
} else if (avg >= 60.0) {
    grade = "D";
} else {
    grade = "F";
}
System.out.println("Grade is  " + grade);

Also, for ranges issue, I just discovered NavigableMap can be used like

NavigableMap<Double, String> map = new TreeMap<>();
map.put(0.0, "F");
map.put(60.0, "D");
map.put(70.0, "C");
map.put(80.0, "B");
map.put(90.0, "A");
System.out.println("Grade is " + map.floorEntry(avg).getValue());

Details here Using java map for range searches

azro
  • 53,056
  • 7
  • 34
  • 70