我是java的新手,在尝试将单个元素添加到结构类型数组时遇到问题。我有我的数组设置:public apartment availableRoom[] = new apartment[1];
我的主要调用一个方法,一旦应用程序启动就初始化它:
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;
}
答案 0 :(得分:1)
好吧,就像你说的那样
没有错误,但是当我打印房间的信息时,它返回每个值为0,并将guest返回为null。
我认为,您在不同的对象中设置值并打印不同的对象。如果您只是粘贴打印其值的方式,它可能会有很大帮助。
需要考虑的事项
答案 1 :(得分: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.
中找到更多详情