简体   繁体   中英

Java: Using switch statements for multi expressions?

Two questions. I hear it is best to use switch statements when you would have more than 3 'if' statements. Is that the case?

Secondly, could someone review the following code and give me an idea on A. How to convert into a switch statement albeit being multi expression or B. explaining why the variable 'grade' always results in F.

while (!"Y".equalsIgnoreCase(exit)) 
         {
                i++;
                System.out.print("Please enter name of assignment " + i + ": ");
                assignment = user.nextLine().toUpperCase(); //consumes string + \n
                System.out.print("Please enter points earned: ");
                earned = user.nextDouble();//consumes double
                user.nextLine();//consumes \n
                System.out.print("Please enter total points possible: ");
                total = user.nextDouble();
                user.nextLine();



        System.out.print("Assignment\t"); System.out.print("Score\t"); System.out.print("Total Points\t"); System.out.print("Percentage\t\n");


        System.out.print(assignment + "\t\t"); System.out.print(earned + "\t"); System.out.print(total + "\t\t"); System.out.print(percent.format(earned / total) + "\n\t");


         // Putting user data into an array for calculation:
          double[] calc; calc = new double[4];   
                calc[i] = earned; // Array elements coincide with the current iteration loop

          double[] totalPoints; totalPoints = new double[4];
                totalPoints[i] = total;


         for ( double e : calc) // adds up all the stored data in the array
            sum += e;


         for ( double f : totalPoints) // adds up all the stored data in the array
            tot += f;




     char grade = '0';
            if (sum / tot >= 90) 
            {
                grade = 'A';
            }

            else if (sum / tot >= 80 && sum / tot <= 89.99)
            {
                grade = 'B';
            }

            else if (sum / tot >= 70 && sum / tot <= 79.99)
            {
                grade = 'C';

            }

            else if (sum / tot >= 60 && sum / tot <= 69.99)
            {
                grade = 'D';

            }

            else if (sum / tot <= 59.99)
            {
                grade = 'F';

            }
        System.out.println("Your total is " + sum + " out of " + tot + ", or " + percent.format(sum / tot) + ", and your grade is an " + grade );   

        }

I don't think a switch case would work very well in this case, but like keppil said above, you should evaluate the if statements with a float with a different threshold ie

private float total = sum/tot * 100;

if(total >= 90){ //etc...

Because as it stands right now ill bet that sum/tot evaluates to a decimal

When there is a range of values that need to be checked for, then if statements are suitable.
When you have specific values to check for, switch statements are suitable.

In your code, if statements are just fine. Though you can improve it by writing something like following:

public class Grade
{
  public Grade()
  {
    float score = 95;
    float total = 100;

    char grade = getGrade(score);

    System.out.println("Score: " + score);
    System.out.println("Total: " + total);
    System.out.println("Grade: " + grade);
  }

  private char getGrade(float score)
  {
    char grade = 'F';

    if (score >= 90)
      grade = 'A';

    else if (score >= 80)
      grade = 'B';

    else if (score >= 70)
      grade = 'C';

    else if (score >= 60)
      grade = 'D';

    return grade;
  }

  public static void main(String[] args)
  {
    new Grade();
  }
}

As @Keppil mentioned, sum / tot probably always yields a value between 0 and 1 . You might want to change the thresholds you're comparing it too (ie: 0.9 instead of 90 and so on).

On the other hand, when you haven't satisfied the if (sum / tot >= 90) condition, you know for sure that sum / tot is strictly less than 90 . Thus, you don't need to check in the following test if sum / tot <= 89.99 . By the way, that would be dangerous: imagine if sum / tot == 89.999 ? None of your conditions would be satisfied.

I would recommend to create a method that yields the grade, like this:

public static char gradeFor(final float tot, final float sum) {
    float ratio = tot / sum;

    if(ratio >= 0.9f) {
        return 'A';
    }

    if(ratio >= 0.8f) {
        return 'B';
    }

    if(ratio >= 0.7f) {
        return 'C';
    }

    if(ratio >= 0.6f) {
        return 'D';
    }

    if(ratio >= 0.5f) {
        return 'E';
    }

    return 'F';
}

One last thing: it seems that there is no case in which you may return E ... is it intended?

To summarize, I believe that you might wanna look into this:

  • make sure that tot and sum are decimal values
  • make sure that your thresholds match the values you're testing against (you'll most probably have to divide them by 100f , as @Keppil mentioned)
  • make sure that there is no corner case missed (like if tot / sum is greater than 89.99 AND lower than 90 )
  • make sure that the behavior you implemented is what you intended to do (the fact that you can never return 'E' kinda bothers me :p)

Cheers!

A switch statement is not always good to use.Why?Well, switch statements only work with primitive data types and enumerated types. However, you can use wrapper classes for primitive types like bytes, doubles, int, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM