3 回答
TA贡献1846条经验 获得超7个赞
您的代码有 3 个问题:
您永远不会初始化内部数组。用 来做
arr[z] = new char[s.length()];。你定义的方式
arrOfStr。您用空白子字符串分割字符串。相反,只需像这样s使用:charAtarr[z][y] = s.charAt(y);nextInt正如评论所建议的那样,存在未考虑(输入)字符的问题\n。所以使用int no=Integer.parseInt(in.nextLine());,而不是使用nextInt。
最终代码应如下所示:
for(z=0 ; z<no ; z++)
{
String s = in.nextLine();
arr[z] = new char[s.length()];
for( y =0 ; y<s.length() ; y++)
{
arr[z][y]=s.charAt(y);
}
}
TA贡献1873条经验 获得超9个赞
试试这个代码:
第一个问题是您没有初始化内部数组。此外,您同时使用了nextInt()和nextLine()。该nextInt()方法不考虑您的 \n(newLine symbol) 。所以该nextLine()方法会直接消费它,不会考虑你后续的输入。
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
Integer no;
do { // this is some flaky code but it works for this purpose
try {
no = Integer.parseInt(in.nextLine());
break;
} catch (Exception e) {
System.out.println("please enter only a numeric value");
}
} while (true);
System.out.println("You entered string " + no);
int z = 0, y = 0;
char[][] arr = new char[no][];
for (z = 0; z < no; z++) {
String s = in.nextLine();
String[] arrOfStr = s.split("");
arr[z] = new char[arrOfStr.length];
for (y = 0; y < arrOfStr.length; y++) {
System.out.println();
arr[z][y] = arrOfStr[y].charAt(0);
}
}
for (char[] charArr : arr) {
for (char c : charArr) {
System.out.println(c);
}
}
}
}
TA贡献1827条经验 获得超8个赞
在java二维数组中最初是1D array of arrays. 这不是C++:
您只需知道行数即可;
每个子数组(一行)可以有不同的长度。
String[][] matrix = new String[3][]; // declare an 2D array with 3 rows and not define column length
matrix[0] = new String[5]; // 1st line has 5 columns; matrix[0][4] is the last column of 1st row
matrix[1] = new String[10]; // 2nd line has 10 columns; matrix[1][9] is the last column of 2nd row
// matrix[2] == null -> true // 3rd line is not initialized
String[][] matrix = new String[2][2]; // declare 2D array and initialize all rows with 1D sub-array with 2 columns (i.e. we have a square).
添加回答
举报
