gpt4 book ai didi

java - 与构造函数一起工作并且极度困惑

转载 作者:行者123 更新时间:2023-12-01 18:48:12 26 4
gpt4 key购买 nike

这是我第一次尝试使用“构造函数”做任何事情,在四处寻找有关该主题的帮助一个小时左右后,我仍然觉得我不知道自己在做什么。

这是我为另一个程序创建的类文件,它应该有 2 个构造函数。我尽力了,但编译器一直告诉我我需要标识符。

如何识别构造函数?

   public class property
{
int storey = 0;
int width = 0;
int length = 0;

property(int storey, int width, int length)
{
{
this.storey = storey;
this.width = width;
this.length = length;
}

}

property(int width, int length)
{
this(1, width, length);

}


public int calculateArea(int area)
{

return (storey * width * length);

}

public double calculatePrice(double price)
{

return (((storey * width * length) * 2.24) *1.15);

}

}

最佳答案

编译器告诉您需要指定 p1p2 变量的类型。例如:

property(int p1)
{
// constructor
}

其他一些建议:

  • 类名称应采用大驼峰式命名,即 Property
  • 两个构造函数都为自己分配字段,您应该指定 storeywidthlength 作为构造函数参数,然后使用 this 关键字将它们分配给字段:

Property(int storey, int width, int length)
{
this.storey = storey;
this.width = width;
this.length = length;
}
  • 当您想在构造函数中使用默认值时,您可以调用其他构造函数:

Property(int width, int length)
{
this(1, width, length);
}
  • calculateAreacalculatePrice 应返回计算值。分配给参数不会产生任何效果:

public int calculateArea()
{
return (storey * width * length);
}
  • 为属性字段添加访问器:

public int getStorey()
{
return storey;
}

然后您可以使用您的属性(property),例如:

BufferedReader br = new BufferedReader(System.in); 
System.out.println("storey: ");
int storey = Integer.parseInt(br.readLine());

System.out.println("width: ");
int width = Integer.parseInt(br.readLine());

System.out.println("length: ");
int length = Integer.parseInt(br.readLine());

Property p = new Property(storey, width, length);
System.out.println("property dimensions:width " + p.calculateArea());
System.out.println("width: " + p.getWidth());
System.out.println("length: " + p.getLength());
System.out.println("storeys: " + p.getStoreys());
System.out.println("area: " + p.calculateArea());
System.out.println("price: " + p.calculatePrice());

关于java - 与构造函数一起工作并且极度困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16783090/

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