[英]How can i convert my if and else-if statements into a switch case?
I've recently started learning Java.我最近开始学习 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.
我的老师给了我们这个家庭作业,它是关于编写下面的 If-Else 语句代码并将其转换为 Switch-Case 语句代码。 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.
我正确编写了 If-Else 语句代码,但我无法将 if 和 else-if 转换为 switch case 语句。 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.我尝试添加一个开关,然后将每个数字更改为案例 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.");
}
all this is correct but i just dont know where and how to put the switch cases into this program.所有这些都是正确的,但我只是不知道在哪里以及如何将开关盒放入该程序中。
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现在,让这种类型的解决方案适应您的实际问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.