[英]Java NullPointerException 2D array initialized in constructor, but method refuses to acknowledge
[英]Instantiating a 2d array in a java constructor?
我感到很困惑。 我需要創建一個構造函數來創建一個帶有從main方法調用的參數的二維數組。每次我在同一個類的另一個方法中調用Seats 2D數組時,我都會收到錯誤。 為什么這樣,我如何使用我在構造函數中創建的數組?
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]);
}
您處於良好的軌道上,但您必須制作Seats
實例變量才能獲得正確的結果:
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] = "???";
}
}
}
將構造函數外部的數組聲明為私有變量:
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]);
}
}
class MovieSeating{
private String[][] seats;
public MovieSeating(int col, int row){
seats = new String[row][col];
}
}
使座位成為實例變量以增加其范圍。
Seats
在main
是未知的,只有在構造函數的范圍內才知道。
你應該使它成為一個類成員並在構造函數中初始化它:
class MovieSeating {
private String [][] Seats;
..
public MovieSeating(int rowNum, int columnNum) {
Seats = new String[rowNum][columnNum];
..
}
}
在這里我發送代碼剪切我希望這將有助於你
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]); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.