Search code examples
javamethodsswitch-statementreturn

How do i use switch statement inside a method such that the method can return a char value which is acquired by the switch statement inside it?


This method is suppose to calculate the average of the scores obtained and return the grade accordingly. How do i pass the grade from switch() to the calculate() so that it could return the right grade?

public char calculate(){

    int count=0;
    int total = 0;
     for (int x: testScores){
             total = total + x;
             count++;
     }  

     int grade = total/count;

        switch(grade){
                case (1): if (grade>=90) return 'O';
                break;
                case(2): if (grade>=80 && grade<90) return 'E';
                break;
                case (3): if (grade>=70 && grade<80) return 'A';
                break;
                case (4): if (grade>=55 && grade<70) return 'P';
                break;
                case (5): if (grade>=40 && grade<55) return 'D';
                break;
                case (6): if (grade<40) return 'E';
                break;
            }
            return //what should i return here??

    }

i know how to do it without switch(), but i think it could be done this way as well. plz tell me what am i missing?


Solution

  • Concerning your question:

    • the last return is not needed, just end switch with default clause and return default value there.
    • there is no need to use break stetements, since you are using return on each case

    Also, if you are limiting yourself to only use switch, then this is one simpler way to achieve your goal:

    char calculate(int[] scores) {
      double averageScore = Arrays.stream(scores).average().getAsDouble();
      int nearestMultipleOfFive = 5 * ((int) averageScore / 5);
      switch (nearestMultipleOfFive) {
        case 100:
        case 95: 
        case 90: return 'O';
        case 85:
        case 80: return 'E';
        case 75: 
        case 70: return 'A';
        case 65: 
        case 60:
        case 55: return 'P';
        case 50: 
        case 45:
        case 40: return 'D';
        default: return 'E';
      }
    }