关于java字符串,二维的String[][]的问题,小菜求教
请看代码如下:
public class yyy {
public static void main(String[] args) {
String[][] str={
{"傻","66","32","98","false"},
{"傻","82","69","128","true"},
{"傻","96","69","128","true"},
{"傻","82","78","128","true"},
};
System.out.println("---原始数据如下:");
for(int i = 0 ; i<str.length ; i++ )
{
for(int j =0 ; j < str[i].length ; j++ )
System.out.print(str[i][j]+" ");
System.out.println();
}
System.out.println("---赋值的数据如下:");
int rows = str.length;//获取str的行
int cols = str[0].length;//获取str的列
String [][] copyStr = null ;
for(int i =0; i<rows ; i++){
copyStr[i] = new String[cols];//为每一行分配跟str一样大小的列
for(int j = 0 ; j<cols ; j++ ){
copyStr[i][j] = new String(); //为每一个列元素开辟空间
copyStr[i][j] = str[i][j]; //把str的元素赋值给copyStr
System.out.print(copyStr[i][j]);//输出
}
System.out.println();//空格
}
}
}
问题,出现了
空指针异常!
根据Eclipse提示,问题出在copyStr[i] = new String[cols];
但是我不知道此处怎么改?于是我加了条代码copyStr = new String[rows];妄图分配空间,但这样更错!
我很纠结,不知道怎么办了!
能否指教我下,修改我的错误!谢谢!
------解决方案--------------------
没有初始化
String[][] copyStr = new String[rows][cols];
------解决方案--------------------public class Test2 {
public static void main(String[] args) {
String[][] str={
{"傻","66","32","98","false"},
{"傻","82","69","128","true"},
{"傻","96","69","128","true"},
{"傻","82","78","128","true"},
};
System.out.println("---原始数据如下:");
for(int i = 0 ; i<str.length ; i++ )
{
for(int j =0 ; j < str[i].length ; j++ )
System.out.print(str[i][j]+" ");
System.out.println();
}
System.out.println("---赋值的数据如下:");
int rows = str.length;//获取str的行
int cols = str[0].length;//获取str的列
String [][] copyStr = new String[str.length][str[0].length] ;