我创建了一个带有switch语句的类,它根据用户选择的边数打印出多边形的名称。我无法弄清楚的问题是当一个边小于3且超过12时如何做到这一点。我宁愿使用if语句,但我不能解决这个问题。因为我可以使用一个案例:对于12个以上的每个数字,例如案例13:,案例14:等等。我该怎么办?
import java.util.Scanner;
public class Lab13 {
public static void main(String[] args) {
int sides = 0;
Scanner scan = new Scanner(System. in );
System.out.println("Please enter the number of sides of your Polygon");
sides = scan.nextInt();
String polygonname = "";
switch (sides) {
case 3:
polygonname = polygonname + "triangle";
break;
case 4:
polygonname = polygonname + "square";
break;
case 5:
polygonname = polygonname + "pentagon";
break;
case 6:
polygonname = polygonname + "hexagon";
break;
case 7:
polygonname = polygonname + "heptagon";
break;
case 8:
polygonname = polygonname + "octagon";
break;
case 9:
polygonname = polygonname + "nonagon";
break;
case 10:
polygonname = polygonname + "decagon";
break;
case 12:
polygonname = polygonname + "dodecagon";
break;
}
System.out.print("A polygon with " + sides + " sides is called a " + polygonname + ".");
}
}
答案 0 :(得分:5)
在default:
的末尾使用switch
,它将处理所有其他情况,就像{else
中的if / else if / else if
一样1}}陈述。写得像这样:
switch(sides) {
case 3:
polygonname=polygonname+"triangle";
break;
// ...
default:
polygonname=polygonname+"unknown";
break;
}
答案 1 :(得分:0)
你应该接受奥斯卡的回答。在final
进行switch/case
时,我只是添加了我的观点来说明final
是一种很好的做法。遗憾的是,Java的Switch语句不是基于表达式的,也不是详尽无遗的。您可以通过使用 final String polygonname;
switch (sides) {
case 3:
polygonname = "triangle";
break;
case 4:
polygonname = "square";
break;
// Other cases....
case 10:
polygonname = "decagon";
break;
case 12:
polygonname = "dodecagon";
break;
default:
polygonname = "n-gon";
}
变量来解决这个问题,如果您不处理案例,编译器就会生气。
{{1}}