【发布时间】:2014-03-02 11:39:48
【问题描述】:
如何在不在类中创建私有变量的情况下将长度和宽度变量调用到 getArea 方法中,我这样做的方式是导致该方法在它已经运行一次后再次运行。我真的不喜欢这种方式,但教授希望它这样做来模拟“面向对象编程”之前的时代
/*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方法中的变量呢?
-
斯蒂芬,她只想要主要的方法,而不是我提示用户的消息,
-
如果方法只能在main中调用,我的答案绝对是解决方案。
标签: java variables methods call