Reputation: 215
I am so confused. I need to make a constructor to create a 2d array with parameters called from main method.. Every time I call the Seats 2D array in another method of the same class, I get an error. Why is that and how do I use the array I made in the constructor?
class MovieSeating
{
public MovieSeating(int rowNum, int columnNum)
{
String [][] Seats = new String[rowNum][columnNum];
for (int r = 0; r < rowNum; r++)
{
for (int c = 0; c < columnNum; c++)
{
Seats[r][c] = "???";
}
}
}
private Customer getCustomerAt(int row, int col)
{
System.out.println("Customer at row " + row + " and col " + col + "." );
System.out.println(Seats[row][col]);
}
Upvotes: 3
Views: 35739
Reputation: 501
Here i am sending code snipped i hope this will help u
public Charts(int graph_min, int graph_max, double[] dataset, int stepSize,double[][] percentRange) {
//here double[][]={{10},{100}};
this(graph_min,graph_max,dataset);
this.stepSize = stepSize;
System.out.println("double constructor "+percentRange.length);
this.percentRange = new double[percentRange.length][percentRange[0].length];
System.out.println("percentRange: "+this.percentRange);
for (int i = 0; i < percentRange.length; i++) {
for (int j = 0; j < percentRange[i].length; j++) {
this.percentRange[i][j] = percentRange[i][j];
System.out.println("ps_Axis constructor valuesd "+this.percentRange[i][j]);
}
}
Upvotes: 0
Reputation: 2445
Declare the array outside the constructor as a private variable :
class MovieSeating
{
private String [][] Seats;
public MovieSeating(int rowNum, int columnNum)
{
Seats = new String[rowNum][columnNum];
for (int r = 0; r < rowNum; r++)
{
for (int c = 0; c < columnNum; c++)
{
Seats[r][c] = "???";
}
}
}
private void getCustomerAt(int row, int col)
{
System.out.println("Customer at row " + row + " and col " + col + "." );
System.out.println(Seats[row][col]);
}
}
Upvotes: 1
Reputation: 41935
class MovieSeating{
private String[][] seats;
public MovieSeating(int col, int row){
seats = new String[row][col];
}
}
Make seats an instance variable to increase the scope of it.
Upvotes: 0
Reputation: 10707
You are on a good track, but you have to make Seats
instance variable in order to get proper results:
private String [][] Seats;
public MovieSeating(int rowNum, int columnNum)
{
Seats = new String[rowNum][columnNum];
for (int r = 0; r < rowNum; r++)
{
for (int c = 0; c < columnNum; c++)
{
Seats[r][c] = "???";
}
}
}
Upvotes: 3
Reputation: 95948
Seats
is not known in the main
, it's known only in the scope of the constructor.
You should make it a class member and initialize it in the constructor:
class MovieSeating {
private String [][] Seats;
..
public MovieSeating(int rowNum, int columnNum) {
Seats = new String[rowNum][columnNum];
..
}
}
Upvotes: 0