gpt4 book ai didi

java - 我试图将双变量从一种方法调用到另一种方法中

转载 作者:行者123 更新时间:2023-12-01 08:06:01 25 4
gpt4 key购买 nike

如何将长度和宽度变量调用到 getArea 方法中,而不在类中创建私有(private)变量,我这样做的方式是导致该方法在已经运行一次后再次运行。我真的不喜欢这种方式,但这就是教授希望的方式来模拟“面向对象编程”之前的时代

/*This program allows the user to enter the length and widtch and receive the area
of the rectangle*/

import java.util.Scanner;

public class theRectangleCompany
{
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getLength();
getWidth();
getArea();
}

public static double getLength()
{
double length;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the length ");
length = keyboard.nextDouble();
return length;
}

public static double getWidth()
{
double width;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the width ");
width = keyboard.nextDouble();
return width;
}

public static void getArea()
{
double length = getLength();
double width = getWidth();
double area = width * length;
System.out.println("The area of the Rectangle is: " +area);

}


}

最佳答案

为什么要从 main 方法调用 getLength() 和 getWidth()。只需调用 getArea()

public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getArea();
}

关于java - 我试图将双变量从一种方法调用到另一种方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21587447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com