gpt4 book ai didi

java - 访问对象数组项,java

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

我使用数组语句创建了一个数字对象,并且可以在创建类时打印类中传递的值,但是当我尝试从类外部(monopolygame 类)检索元素值时,它不会识别引用 - 我怎样才能正确引用它?

public class monopolygame {

public static void main(String[] args) {

//set up array of 18 objects
property properties[] = new property[18];

//create 18 property objects and populate array
properties[0] = new property("a","available",400,500);//create property
properties[1] = new property("b","available",400,500);//create property
properties[2] = new property("c","available",200,300);//create property
properties[3] = new property("d","available",100,180);//create property
properties[4] = new property("e","available",400,700);//create property
}
}

属性类别...

public class property
{
public static void main(String[] args)
{
}

//constructor
public property(String propertyname, String owner, double price, double rent)
{
System.out.println("Property info for " + propertyname
+ " - Rent : £" + rent
+ "Price : £" + price
+ "owned by :" + owner);
}
}

我在垄断类中使用这种引用来尝试访问数据

if (properties[2].propertyname == "available")
{
System.out.println("avaialble");
}
else
{
System.out.println("sold");
}

谢谢

最佳答案

您必须首先在“property”类中声明这些属性:

class property  {
String propertyname;
String owner;
int price;
int rent;
public Property( String somename, String owner, int price, int rent ) {
this.propertyname = somename;
this.owner = owner;
this.price = price;
this.rent = rent;
// and so on
}
}

您使用的数组是 main 方法的本地数组。

要在 main 方法的范围之外访问它,您应该将其声明为 class 属性或 instance 属性,如下所示:

public class monopolygame {
public static property properties[];
public static void main(String[] args) {
//set up array of 18 objects

properties = new property[18];
.....

这样你就可以用其他方法访问数组,如下所示:

    public void setUp() {
for( property p : properties ) {
System.out.println( p.propertyname ); // etc.

然后你的代码:

if (properties[2].propertyname == "available")

会起作用的。

顺便说一句,Java中所有类名按照惯例都以大写开头,所以应该是:

Property 代替 propertyMonopolyGame 代替 monopolygame

关于java - 访问对象数组项,java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1800981/

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