嗨,我已经完成了在指南的帮助下进行三角面积计算的基本代码。然后,我添加了一些代码以使其更有趣,但我希望在得到结果后将其重置。我希望程序在使用有效值完成之前的计算之后,将其重置为“输入三角形的底数:”。如果在(x)时间过后重置,那将是很好的。
我只是想让它在完成任务后按虚拟计算器中的C按钮。
代码:
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class TriangleArea {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
//declare variables to hold the base and height
double base;
double height;
//Variables created. move on
System.out.print("Enter the triangle's base: ");
base = sc.nextDouble();
//Base has been declared and filled in
System.out.print("Enter the triangle's height: ");
height = sc.nextDouble();
//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);
int Outcome;
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 {
}
}
}
答案 0 :(得分:0)
您想使用退出用户的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");
}
}
答案 1 :(得分:-1)
我认为您需要做
while (true){
your code
if (exit condition){
break;
}
}
这样,您的程序就会循环运行。