Search code examples
javaswitch-statementjoptionpane

How can i convert my if and else-if statements into a switch case?


I've recently started learning Java. My teacher has given us this homework assignment which is about writing and converting the If-Else statement code below into a Switch-Case statement code. I wrote the If-Else statement code correctly but i haven't been able to convert my if and else-if to a switch case statements. The sooner I can get an answer the better. Thank you.

ive tried adding a switch and then changing each number to case 1, case 2,etc.

import javax.swing.JOptionPane;

public class ExerciseV {
  public static void main(String [] args){

 String rating;
    String performance;

     rating = JOptionPane.showInputDialog("What is your rating for the gymnast from (1-10)?");

     if(rating.equalsIgnoreCase("One")||rating.equalsIgnoreCase("one")||rating.equalsIgnoreCase("1")||
        rating.equals("Two")||rating.equalsIgnoreCase("two")||rating.equalsIgnoreCase("2")||
        rating.equals("Three")||rating.equalsIgnoreCase("three")||rating.equalsIgnoreCase("3")){
     System.out.println("You scored the performance a rating of: " + rating);
          performance = "BAD";
     System.out.println("You typed in the number "+ rating +" so they had a "+ performance +" performance.");
     }
     else if(rating.equals("Four")||rating.equalsIgnoreCase("four")||rating.equalsIgnoreCase("4")||
             rating.equals("Five")||rating.equalsIgnoreCase("five")||rating.equalsIgnoreCase("5")||
        rating.equals("Six")||rating.equalsIgnoreCase("six")||rating.equalsIgnoreCase("6")){
     System.out.println("You scored the performance a rating of: " + rating);
          performance = "AVERAGE";
     System.out.println("You typed in the number "+rating+" so they had a "+performance+" performance.");
     }

all this is correct but i just dont know where and how to put the switch cases into this program.


Solution

  • I think this code could help you

    switch(rating.toUpperCase()) { 
            case "ONE":
            case "1":
            case "TWO":
            case "2":
                performance = "BAD";
                break;
    
            case "THREE":
            case "3":
            //...
        }
    

    Now, adapt this type of solution to your real problem