所以我是初學者;任務(wù)是將給定的字符串轉(zhuǎn)換為數(shù)組,字符串總是以第一個字符作為行數(shù),第二個字符作為列數(shù)。我的問題是解決如何將字符串 's' 的其余部分從一維數(shù)組移動到二維數(shù)組中。提前致謝!import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] s = scanner.nextLine().split(" "); int arows = Integer.parseInt(s[0]); int acols = Integer.parseInt(s[1]); int[][] cells = new int[arows][acols]; for (int col = 0; col < acols; col++){ for (int row = 0; row <= arows;row++){ cells[row][col] = Integer.parseInt(s[2]); } } } }
2 回答

蕪湖不蕪
TA貢獻1796條經(jīng)驗 獲得超7個贊
您需要為 for 循環(huán)實現(xiàn)一個計數(shù)器以遍歷輸入字符串。你現(xiàn)在正在做的是用你的字符串的第三個元素填充你的二維數(shù)組。
一種解決方案是只聲明一個變量 i = 2,并為內(nèi)部 for 循環(huán)的每次傳遞增加它。
int i = 2
for (int col = 0; col < acols; col++){
for (int row = 0; row < arows;row++){
cells[row][col] = Integer.parseInt(s[i]);
i++;
}
}
編輯:刪除 <= 在行循環(huán)中,將索引的初始值更改為 2

慕仙森
TA貢獻1827條經(jīng)驗 獲得超8個贊
這就是解決方案,你必須再放一個迭代器,并把它初始化為2,這樣就跳過了s[]的前兩個元素
int i = 2;
for (int col = 0; col < acols; col++){
for (int row = 0; row < arows;row++){
cells[row][col] = Integer.parseInt(s[i]);
i++;
}
}
添加回答
舉報
0/150
提交
取消