gpt4 book ai didi

java - java中将变量值从一个类传递到另一个类

转载 作者:行者123 更新时间:2023-11-30 02:40:40 25 4
gpt4 key购买 nike

我有一个 Java 程序,其中我获取用户输入的长度和宽度并计算总面积和周长。根据练习说明,它使用两个类:Main 和 Rectangle。我遇到的问题是我不知道如何将长度和宽度值从主类传递到 Rectangle 类。当我运行该程序时,它只给我零值,并告诉我主类中的局部变量(长度和宽度)没有被使用。我只能在 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;
}

}

最佳答案

您需要调用 setter 来更新字段:

Rectangle rectangle = new Rectangle();
rectangle.setLength(length);
rectangle.setWidth(width);

旁注:“高度”是比“长度”更传统且更明确的术语。

关于java - java中将变量值从一个类传递到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41819471/

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