当我尝试将2d数组(myString
)传递给构造函数时,Eclipse在以下行中向我显示NullPointerException
:
DenseBoard<String> temp1 = new DenseBoard<String>(myString, "a");
smb可以请我解释一下我做错了什么吗?提前致谢!
public class Tester {
public static void main(String[] args){
String[][] myString = {{"A B C"}, {"D E F"}, {"G H I"}};
DenseBoard<String> temp1 = new DenseBoard<String>(myString, "a");
System.out.println(temp1);
}
}
类密集板
import java.util.*;
public class DenseBoard <T> {
private ArrayList<ArrayList<T>> myBoard;
public DenseBoard(T[][] x, T fillElem){
for(int i = 0; i < x.length; i++){
ArrayList<T> values = new ArrayList<T>();
for(int j = 0; j < x[0].length; j++){
values.add(x[i][j]);
}
myBoard.add(values);
}
}
public String toString(){
String result = "";
for(int i = 0; i < myBoard.size(); i++){
for(int j = 0; j < myBoard.get(i).size(); j++){
result += myBoard.get(i).get(j);
}
System.out.println();
}
return result;
}
}
最佳答案
您尚未初始化变量myBoard
,并且在for循环中必须使用x[i].length
而不是x[0].length
尝试这个:-
package p1;
import java.util.ArrayList;
public class A1{
public static void main(String[] args) {
String[][] myString = {{"A B C"}, {"D E F"}, {"G H I"}};
DenseBoard<String> temp1 = new DenseBoard<String>(myString, "a");
System.out.println(temp1);
}
}
class DenseBoard <T> {
private ArrayList<ArrayList<T>> myBoard;
public DenseBoard(T[][] x, T fillElem){
myBoard = new ArrayList<>();
for(int i = 0; i < x.length; i++){
ArrayList<T> values = new ArrayList<T>();
for(int j = 0; j < x[i].length; j++){
values.add(x[i][j]);
}
System.out.println(i);
System.out.println(values);
myBoard.add(values);
}
}
public String toString(){
String result = "";
for(int i = 0; i < myBoard.size(); i++){
for(int j = 0; j < myBoard.get(i).size(); j++){
result += myBoard.get(i).get(j);
}
System.out.println();
}
return result;
}
}
关于java - 将2d数组传递给构造函数时发生NullPointerException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32410081/