我有这个Java程序,我在其中获取用户的长度和宽度输入,并计算总面积和周长。根据练习说明,它使用两个类,Main和Rectangle。我遇到的问题是我不知道如何将长度和宽度值从主类传递给Rectangle类。当我运行程序时,它只给我零值,并告诉我不使用Main类中的局部变量(长度和宽度)。我只能在Rectangle类中使用零参数构造函数,因为这是练习所要求的。我知道如何通过使用接受两个参数(长度和宽度)的不同构造函数来使程序工作。我已经谷歌搜索并查看了整个论坛,但我仍然无法弄清楚这一点。有人可以给我一些提示,谢谢。
这是主要课程。
package murach.rectangle;
import java.util.Scanner;
import murach.rectangle.Rectangle;
public class Main {
public static void main(String args[]) {
System.out.println("Welcome to the Area and Perimeter Calculator");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get input from user
System.out.print("Enter length: ");
double length = Double.parseDouble(sc.nextLine());
System.out.print("Enter width: ");
double width = Double.parseDouble(sc.nextLine());
Rectangle rectangle = new Rectangle();
String message =
"Area: " + rectangle.getAreaNumberFormat() + "\n" +
"Perimeter: " + rectangle.getPerimeterNumberFormat() + "\n";
System.out.println(message);
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
sc.close();
System.out.println("Bye!");
}
}
这是Rectangle类。
package murach.rectangle;
import java.text.NumberFormat;
public class Rectangle {
private double width;
private double length;
public Rectangle() {
width = 0;
length = 0;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getArea() {
double area = length * width;
return area;
}
public double getPerimeter() {
double perimeter = 2 * width + 2 * length;
return perimeter;
}
public String getAreaNumberFormat() {
NumberFormat number = NumberFormat.getNumberInstance();
number.setMinimumFractionDigits(3);
String numberAreaFormatted = number.format(width);
return numberAreaFormatted;
}
public String getPerimeterNumberFormat() {
NumberFormat number = NumberFormat.getNumberInstance();
number.setMinimumFractionDigits(3);
String numberPerimeterFormatted = number.format(length);
return numberPerimeterFormatted;
}
}
答案 0 :(得分:2)
您需要致电您的setter来更新字段:
Rectangle rectangle = new Rectangle();
rectangle.setLength(length);
rectangle.setWidth(width);
旁注:"身高"一个术语比#长度更常规,更不模糊。