2 回答
TA贡献1865条经验 获得超7个赞
您想使用退出的 while 循环,例如,通过让用户输入“0”作为退出代码。您可以使用boolean初始化为 true 并在用户输入退出代码时设置为 false 的 。
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
boolean repeat = true;
while (repeat) {
// declare variables to hold the base and height
double base;
double height;
// Variables created. move on
System.out.print("Enter the triangle's base (enter 0 to exit): ");
base = sc.nextDouble();
if (base == 0) {
repeat = false;
break;
}
// Base has been declared and filled in
System.out.print("Enter the triangle's height (enter 0 to exit): ");
height = sc.nextDouble();
if (height == 0) {
repeat = false;
break;
}
// Both variables are filled in
double preArea = base * height;
// now we need to divide by 2
double Area = preArea / 2;
// There we go. All variables are done, area has been calculated.
System.out.println("The area of your triangle is: " + Area);
if (Area <= 100) {
System.out.println("Triangle's area is small");
}
if (Area <= 300) {
System.out.println("Triangles size is medium");
}
if (Area >= 300) {
System.out.println("Triangle's area is big");
}
else {
}
}
System.out.println("Bye bye");
}
}
TA贡献1847条经验 获得超7个赞
我认为你需要做
while (true){
your code
if (exit condition){
break;
}
}
这样你的程序就会循环。
添加回答
举报