java - 我无法弄清楚为什么我的程序的一部分在继续执行下一个语句之前循环了 4 次

标签 java methods return arguments void

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 的数据。你必须

  1. 获取一次长度和宽度并将其存储(可能在实例变量中)
  2. 随后从您存储它们的位置读取/获取。

关于java - 我无法弄清楚为什么我的程序的一部分在继续执行下一个语句之前循环了 4 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49511185/

相关文章:

java - Java 是 "pass-by-reference"还是 "pass-by-value"?

c - 字符串变量在 C 中未正确返回

c# - 使用 DllImport 将返回的 char* 从 C++ 传递到 C#

java - Play Framework 中子项目类中的包名称(命名空间)

java - 如何使用 java 在 android 中创建 searchIndex

java - Head First Java程序讲解

javascript - 在 JavaScript 中作为方法调用的嵌套函数

java - Eclipse Java 代码模板 -> 方法体 : How do I insert a carriage return?

javascript - 为什么 JavaScript 中的 return 语句不返回任何内容?

java - 我如何通过代码在 Anylogic 中创建路径空间标记元素