[英]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
數據。 你必須
嘗試僅在main中調用displayData()並刪除其他調用。 問題是displayData()本身再次調用其他方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.