簡體   English   中英

在進入下一個語句之前,我無法弄清楚為什么我的程序的一部分循環4次

[英]I can't figure out why part of my program is looping 4 times before moving on to the next statements

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());
        }

}

結果:

輸入矩形的寬度:3

輸入矩形的長度:4

輸入矩形的寬度:3

輸入矩形的長度:4

輸入矩形的寬度:3

輸入矩形的長度:4

輸入矩形的寬度:3

輸入矩形的長度:4

寬度:3.0

長度:4.0

面積:12.0

這是因為你要四次調用getWidth()getLength()

一旦從main
一次來自getArea
一次來自displayData (再次調用getArea

每次調用getWidth()getLength()System.in數據。 你必須

  1. 獲取長度和寬度一次並存儲它(可能在實例變量中)
  2. 隨后從存儲它們的位置讀取/獲取。

嘗試僅在main中調用displayData()並刪除其他調用。 問題是displayData()本身再次調用其他方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM