1

我创建了一个带有 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 + ".");
    }
}
4

2 回答 2

5

default:在 的末尾使用switch,这将处理所有其他情况,就像语句else中的最后一样。if / else if / else if像这样写:

switch(sides) {

case 3:
polygonname=polygonname+"triangle";
break;

// ...

default:
polygonname=polygonname+"unknown";
break;

}
于 2013-04-13T19:51:15.130 回答
0

你应该接受奥斯卡的回答。我添加我的只是为了说明final在做switch/case. 不幸的是,Java 的 Switch 语句不是基于表达式的,也不是详尽无遗的。你可以通过使用final变量来解决这个问题,如果你不处理一个案例,编译器会发疯的。

    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";

    }
于 2013-04-13T20:03:18.703 回答