【发布时间】:2020-02-10 21:16:18
【问题描述】:
对不起,我很难得到这个循环,但我会停止调整它并询问 SO。我希望决策结构循环,我希望它通过输入“4”来停止循环,并且我希望每次都打印“进行选择”提示。谢谢!
public class HW1Geo {
public static void main(String[] args) {
// This program was created in order to allow the user to calculate the areas of rectangles, triangles, and circles.
System.out.println("Thank you for using the MCCH GeoCal program. \nWith this program, you will be able to find the area of three kinds of shapes.\nThis program uses doubles.");
System.out.println();
Scanner keyboard = new Scanner(System.in);
System.out.println("Please make a selection:");
System.out.println("1 - Area of a rectangle");
System.out.println("2 - Area of a triangle");
System.out.println("3 - Area of a circle");
System.out.println("4 - End program");
int select = keyboard.nextInt();
// This decision structure with a nested loop will allow the user to continue to make selections until they decide to quite the program.
while(select != 4) {
if(select == 1) {
System.out.println("Enter the length of the rectangle.");
double length = keyboard.nextDouble();
System.out.println("Enter the width of the rectangle");
double width = keyboard.nextDouble();
System.out.println("The area of the rectangle is: " + rectArea(length, width));
break;
}
else if(select == 2) {
System.out.println("Enter the height of the triangle.");
double height = keyboard.nextDouble();
System.out.println("Enter the size of the base of the triangle.");
double base = keyboard.nextDouble();
System.out.println("The area of the triangle is: " + triArea(height, base));
break;
}
else if(select == 3) {
System.out.println("Enter the radius of the circle.");
double radius = keyboard.nextDouble();
System.out.println("The area of the circle is: " + cirArea(radius));
break;
}
else if(select != 1 && select != 2 && select != 3 && select != 4) {
System.out.println("Incorrect input.");
break;
}
}
System.out.println("Thank you for using this program.");
}
// This method is used to find the area of a rectangle.
public static double rectArea(double length, double width) {
double area = length * width;
return area;
}
public static double triArea(double height, double base) {
double area = 0.5 * base * height;
return area;
}
public static double cirArea(double radius) {
double area = Math.PI * Math.pow(radius, 2);
return area;
}
}
【问题讨论】:
-
只需将提示(菜单)代码行和
select = keyboard.nextInt();行移入 while 循环顶部第一个if 声明。循环上方有:int select;。从int select = keyboard.nextInt();行中删除int类型声明。 -
Also.... 从所有 if 语句代码块中删除
break;语句。
标签: java loops if-statement structure