我最近开始学习Java。我的老师给了我们这个作业,是关于编写下面的If-Else语句代码并将其转换为Switch-Case语句代码。我正确编写了If-Else语句代码,但无法将if和else-if转换为switch case语句。我越早得到答案越好。谢谢。
我尝试添加一个开关,然后将每个数字更改为案例1,案例2等
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.");
}
所有这些都是正确的,但我只是不知道在何处以及如何将开关盒放入该程序。
我认为此代码可以为您提供帮助
switch(rating.toUpperCase()) {
case "ONE":
case "1":
case "TWO":
case "2":
performance = "BAD";
break;
case "THREE":
case "3":
//...
}
现在,使这种类型的解决方案适应您的实际问题