简体   繁体   English

用另一个类的构造函数填充字符串数组

[英]Filling an String Array with a constructor from another class

I am new to programming in Java. 我是Java编程的新手。 We are assigned to create a MovieSeating class which is a 2D array. 我们被分配去创建一个MovieSeating类,它是一个2D数组。 I am stuck on a part where I need to fill each "space" with the information of a customer from a class called Customer I have in another Java file. 我被困在需要用另一个Java文件中名为Customer的类的客户信息填充每个“空间”的部分。

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

I am not sure how to take this info with multiple types and fill it into my 2d array. 我不确定如何获取多种类型的信息并将其填充到我的2d数组中。

Code I currently have, but stuck where to go from here. 我目前拥有的代码,但是卡在了哪里。 Keep getting errors for everything I try. 我尝试的所有内容都会不断出错。

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]= //????????????   
        }
    }
}

Appreciate any insight to set me on the correct path. 感谢任何见识,使我踏上正确的道路。

You can just declare your array like this: 您可以这样声明数组:

Customer[][] seating;

And initialize it like this: 然后像这样初始化它:

seating = new Customer[rowNum][columnNum];

Now you can just assign a new customer to each "space" in the array: 现在,您只需为数组中的每个“空间”分配一个新客户:

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

I also recommend you to add a toString method in the Customer class. 我还建议您在Customer类中添加toString方法。 This way, you can still use a String[][] instead of a 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;
}

Now to assign a Customer to a String[][] , just call toString : 现在要将Customer分配给String[][] ,只需调用toString

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM