关于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();//空格
}
}
}
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();//空格
}
}
}
[解决办法]
public class TwoDimensionTest {
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[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
copyStr[i][j] = new String();
copyStr[i][j] = str[i][j];
System.out.print(copyStr[i][j]);
}
System.out.println();
}
}
}
}
这样也行
[解决办法]
String [][] copyStr = null
copyStr[i] = new String[cols];
请问 copyStr是一个什么? copyStr[i] 是一个什么?
我的理解就是,
copyStr 是一个变量,它是一个"String[][]"类型的变量
copyStr[i] 是一个值,它是一个值不是一个字符串数组类型的变量
[解决办法]
楼主,就是没有初始化嘛!String [][] copyStr = null
[解决办法]
我试了下是把 String[][] copyStr = null改为
String [][] copyStr = new String[rows][cols];
就行了. 上面我说错了