我有對於如何實例化對象的兩維數組的問題。我試圖在一個小樣本下面演示重現我得到的錯誤。如何正確實例化一個兩維數組中的Java
我有這個類名爲節點基本上存儲一個字符。該類在名爲Test的類中用作二維屬性。我使用了一些用戶輸入來建立數組的大小並在instantiate()方法中實例化它。然後,我嘗試使用set方法填充地圖。但是,編譯器給了我以下錯誤信息:
Eclipse的控制檯輸出:
Exception in thread "main" java.lang.NullPointerException at Test.populate(Main.java:44) at Main.main(Main.java:77)
我輸入的是:
Enter height: 3 Enter width: 3
下面是我使用重現此錯誤代碼:
類節點:
class Node {
private char content;
Node(){
this.content = ' ';
}
Node(Node node){
this.content = node.getContent();
}
//Setter
public void setContent(char c) {
this.content = c;
}
//Getter
public char getContent() {
return this.content;
}
}
類檢驗:
class Test {
private Node[][] map;
private int height, width;
public void instantiate(){
Scanner reader = new Scanner(System.in);
System.out.println("Enter height: ");
this.height = reader.nextInt();
System.out.println("Enter width: ");
this.width = reader.nextInt();
map = new Node[height][width];
reader.close();
}
public void populate(){
for(int i=0;i<height;i++)
for(int j=0;j<width;j++){
if((i+j) %2 == 0)
map[i][j].setContent('a');
else
map[i][j].setContent('b');
}
/*
* a b a b
* b a b a ...
* a b a b
* b a b a
* . . .
*/
}
public void print(){
for(int i=0;i<height;i++){
for(int j=0;j<width;j++){
System.out.print(map[i][j].getContent());
}
System.out.println();
}
}
public Node[][] getMap(){
return this.map;
}
}
主要方法:
public class Main {
public static void main(String[] args) {
Test testing = new Test();
testing.instantiate();
testing.populate();
testing.print();
}
}
的代碼也可以在這裏看到:http://pastebin.com/agFMmB38
我還是習慣到Java(從C++來),所以他們有一些我還沒弄明白的差異。
任何幫助將不勝感激。 謝謝!
它的工作!非常感謝你,我一直在爲此奮鬥了幾個小時,而且非常簡單。 – leandrocoutom
總是樂於幫忙! – ifly6