import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
getWidth();
getLength();
getArea();
displayData();
}
public static double getWidth()
{
System.out.print("Enter the width of the rectangle: ");
Scanner keyboard = new Scanner(System.in);
double width = keyboard.nextDouble();
return width;
}
public static double getLength()
{
System.out.print("Enter the length of the rectangle: ");
Scanner keyboard = new Scanner(System.in);
double length = keyboard.nextDouble();
return length;
}
public static double getArea()
{
double area = getWidth() * getLength();
return area;
}
public static void displayData()
{
System.out.println("Width: " + getWidth() +
"\nLength: " + getLength() +
"\nArea: " + getArea());
}
}
结果:
Enter the width of the rectangle: 3
Enter the length of the rectangle: 4
Enter the width of the rectangle: 3
Enter the length of the rectangle: 4
Enter the width of the rectangle: 3
Enter the length of the rectangle: 4
Enter the width of the rectangle: 3
Enter the length of the rectangle: 4
Width: 3.0
Length: 4.0
Area: 12.0
最佳答案
这是因为您调用了 getWidth()
和 getLength()
四次。
一次来自 main
,
一次来自getArea
,
一次来自displayData
(再次调用getArea
)
每次调用 getWidth()
和 getLength()
都会提示来自 System.in
的数据。你必须
- 获取一次长度和宽度并将其存储(可能在实例变量中)
- 随后从您存储它们的位置读取/获取。
关于java - 我无法弄清楚为什么我的程序的一部分在继续执行下一个语句之前循环了 4 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49511185/