3 回答

TA貢獻1846條經驗 獲得超7個贊
您的代碼有 3 個問題:
您永遠不會初始化內部數組。用 來做
arr[z] = new char[s.length()];
。你定義的方式
arrOfStr
。您用空白子字符串分割字符串。相反,只需像這樣s
使用:charAt
arr[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).
添加回答
舉報