使用另一个类的构造函数填充String数组

时间:2016-10-02 21:09:02

标签: java arrays

我是Java编程新手。我们被分配创建一个2DSear的MovieSeating类。我被困在一个部分,我需要用另一个Java文件中名为Customer的类中的客户信息填充每个“空间”。

 public Customer()//constructor
 {
      lastName = "???";
      firstName = "???";
      customerID = 0;
      matineeTickets = 0;
      normalTickets = 0;
      totalCost = 0.0;
  }

我不确定如何将这些信息用于多种类型并将其填充到我的2d数组中。

我目前拥有的代码,但是从这里开始坚持到底。我尝试的一切都会出错。

public class MovieSeating
{
//instance variables
private String [][] seating; //declare array


//create constructor to create Movie Seating array
public MovieSeating(int rowNum, int columnNum)
{

    seating = new String [rowNum][columnNum];

    //for loop to crate an initial customer elember for each part of 

    for (int r = 0; r<rowNum;r++)
    {
        for (int c = 0; c < columnNum; c++)
        {
            seating [r][c]= //????????????   
        }
    }
}

欣赏任何洞察力,让我走上正确的道路。

1 个答案:

答案 0 :(得分:0)

您可以像这样声明您的数组:

Customer[][] seating;

并将其初始化为:

seating = new Customer[rowNum][columnNum];

现在您可以为阵列中的每个“空间”分配一个新客户:

Customer cust = new Customer();
// set fields of cust here...
seating[r][c] = cust;

我还建议您在toString课程中添加Customer方法。这样,您仍然可以使用String[][]代替Customer[][]

@Override
public String toString() {
    // this is just an example, you can add more to the string.
    return "Last Name = " + lastName + ", First Name = " + firstName + ", Customer ID = " + customerID;
}

现在要将Customer分配给String[][],只需致电toString

seating[r][c] = cust.toString();