2013-02-17 106 views
0

我是新来的java和试图将单个元素添加到结构类型数组时遇到问题。我有我的阵列设置为这样:public apartment availableRoom[] = new apartment[1];我的主要要求是,一旦应用程序启动初始化这样的方法:错误添加到结构数组中的单个元素java

availableRoom[0] = new apartment(150, 2, 200.00,null); 
//this sets default values for room#, beds, price, and guest 

我的构造函数有像这样

public apartment(int roomNum, int beds, double price, String guest) 
    { 
     this.roomNumber = roomNum; 
     this.roomBeds = beds; 
     this.nightlyFee = price; 
     this.roomGuest = guest; 
    } 

如果我有问题的信息当我试图分配一个客人到房间。我正在尝试使用availableRoom[i].roomGuest = name名称由用户输入,我设置为0(我选中)。没有错误,但是当我打印房间的信息时,它将每个值都返回为0,并将guest虚拟机返回null。任何人都可以看到我做错了什么? (FYI公寓是从主要一个单独的类)

主要

public class apartmentMain { 


    static apartment action = new apartment(); 



    public static void main(String[] args) { 

     action.createApt(); 
     action.addGuest(); 

apartment.java

public void createApt() 
    { 
     availableRoom[0] = new apartment(150, 2, 200.00,null); 
} 

public void addGuest() 
{ 

    name = input.next(); 
    availableRoom[i].roomGuest = name; 

} 
+1

找到更多的细节可能需要粘贴整个代码 – Ulises 2013-02-17 05:14:37

+0

不,我不认为任何人都可以。这是因为你限制了你发布的内容。我们看不到循环,我们看不到变量的声明,我们不知道如何检查索引的值。鉴于你的问题是什么,你应该能够构建一个完整的,可执行的“主”类,在少于20行的内容中演示你遇到的问题。在创建过程中,你可能只是自己发现答案,如果没有,你可以形成一个更好的问题。 – arcy 2013-02-17 05:15:28

+0

伪代码将会很好 – user1428716 2013-02-17 05:16:09

回答

1

好了,就像你说的

没有错误,但是当我去打印房间的信息,它将每个值返回为0,并将客人返回为null。

我想,你是在不同的对象设置值和打印不同的值。如果您只是粘贴如何打印其值,可能会有很大帮助。

需要考虑的事情

  1. 因为你得到的默认值(即实例变量得到,如果你不指定任何),这意味着实际的对象是有你的阵中,被实例化,但未初始化。
  2. 仔细看看您正在打印哪个对象以及您正在设置哪个值。
  3. 很有可能在第一个索引处插入新实例化的对象,以某种方式替换原来的对象。
  4. 你正在打印一个不同的对象比原来的....一种可能性。
  5. 您可能想要摆脱“无参数构造函数”以更好地实际看到问题。试试吧..值得。
+0

在我尝试添加客人之前,它的打印质量很好。第二我称加客方法,并尝试再次打印是什么时候它返回所有0和空 – bardockyo 2013-02-17 05:41:25

+0

已尝试删除没有参数构造..?也可以。你可能想要显示代码..当你再次打印它.. – Ahmad 2013-02-17 05:47:19

+0

我很抱歉,你可以解释你的意思是没有参数构造? – bardockyo 2013-02-17 05:50:29

0

您的程序不完整。我举了一个小例子,您可以从中猜出您的错误。

public class Demo 
{ 
    int x; 
    public static void main(String args[]) 
    { 
     Demo d[] = new Demo[2]; 
     d[0] = new Demo(); 
     d[1] = new Demo(); 

     d[0].x = 100; 
     d[1].x = 200; 

     System.out.println(d[0].x); 
     System.out.println(d[1].x); 
    } 
} 
Many people get wrong concept in the following code. 
     Demo d[] = new Demo[2]; 

You think a Demo array of 2 elements (with two Demo objects) with object d is created. 
It is wrong. Infact, two reference variables of type Demo are created. The two  
reference variables are to be converted int objects before they are used as follows. 
     d[0] = new Demo(); 
     d[1] = new Demo(); 

With the above code, d[0] and d[1] becomes objects. Now check your code in these 
lines. 

您可以从Java Reference Variables – Objects – Anonymous objects