Reputation: 15
i created a class with switch statement that prints out the name of a polygon based on the number of sides chosen by the user. The problem I cant figure out is how to do this when a side is less than 3 and more than 12. I would have rather liked to have used if statements but I cant for this part. Since I can use a case: for every number over 12 such as case 13:, case 14: etc.. how can I do this?
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 + ".");
}
}
Upvotes: 1
Views: 1058
Reputation: 49075
You should accept Oscar's answer. I only added mine to make a point about final
being a good practice when doing switch/case
. Java's Switch statement is unfortunately not expression based nor exhaustive. You can fix that by using final
variables and the compiler will get mad if you don't handle a case.
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";
}
Upvotes: 0
Reputation: 235984
Use default:
at the end of the switch
, that'll take care of all the other cases, it's like the final else
in an if / else if / else if
statement. Write it like this:
switch(sides) {
case 3:
polygonname=polygonname+"triangle";
break;
// ...
default:
polygonname=polygonname+"unknown";
break;
}
Upvotes: 5