-4

My code is supposed to convert scores to letter grades, so I used if statements. Just wondering if there's a way to use a switch statement instead of if-statements. I have no idea how to convert it. Also, is one better than the other?

   public static void determineGrade(int numArray[], char letterArray[]) {

   int scoreCount = numArray.length;

   for (int i=0; i < scoreCount; i++) {

        if (numArray[i] >= 90 && numArray[i] <=100) {
            letterArray[i] = 'A';
        }           
        if (numArray[i] >= 80 && numArray[i] < 90) {
            letterArray[i] = 'B';

        }
        if (numArray[i] >= 70 && numArray[i] < 80) {
            letterArray[i] = 'C';

        }
        if (numArray[i] >= 60 && numArray[i] < 70) {
            letterArray[i] = 'D';

        }
        if (numArray[i] >= 0 && numArray[i] < 60) {
            letterArray[i] = 'F';
        }
  }
   displayTestScores(numArray, letterArray);
Navi4458
  • 5
  • 4

4 Answers4

1
public char getGrade(int input){
    switch(input/10)
    {
        case 9: return 'A';
        case 8: return 'B';
        case 7: return 'C';
        case 6: return 'D';
        default: return 'F';
    }
}

Then

for (int i=0; i < scoreCount; i++) {
    letterArray[i] = getGrade(numArray[i]);
}
haint504
  • 103
  • 6
0

Your conditions are ranges. Java switch statements have cases for values, not ranges.

Since you have a limited number of cases, you could list each one of them independently. However, this would make your code much longer, with 100 cases.

And there's also some math trickery you could do to find the lower number divisible by 10, and switch on that. But the if statement is simpler to implement and read.

All that said, your second expression in the if statements is unnecessary, if you use an else statement, not an independent if. And you want to use an else, because it would be silly to continue checking all the remaining cases after the first one whose condition is met.

    if (numArray[i] >= 90 ) {  // Can you have values > 100?
        letterArray[i] = 'A';
    }           
    else if (numArray[i] >= 80 ) {  // If we're checking this, we know numArray[i] < 90
        letterArray[i] = 'B';
    }
    else if ... 
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
0

You can switch statement in this case but I wouldn't recommend due to the fact you will have way too many cases. You will use at least 100 cases to input because of your if statement conditions.

case 100 ://code
    break;
case 50 ://skip a bit
case 0 :

There is way too many cases and a waste of time and lines.

Manav Dubey
  • 780
  • 11
  • 26
-1

You're looking to produce a switch statement that has cases based on ranges. It's not really what switch statements are meant for. the if route is more elegant/a better solution for your case imo.

In Java,Using switch statement with a range of value in each case?

Community
  • 1
  • 1
R4N
  • 2,455
  • 1
  • 7
  • 9