![](/img/trans.png)
[英]What is the most efficient way to create a 2d string array of initally repetitive data?
[英]What's the most efficient way to input integers into a 2D array?
這是執行時用戶界面的樣子:
Enter number of rows/columns:
3
1,0,1
1,1,0
0,1,1
所以所有的數字都是用戶輸入的; 創建 3x3 數組很簡單,但我想不出一個好方法來將用戶輸入的矩陣的每一行放入不涉及大量 switch 或 if/else 語句的數組中。
嗯,方陣中元素的總數就是你在那里的數量,平方。
int totalElements = rowsCols * rowsCols;
您可以使用Scanner
讀取循環中的所有元素。 一種方法是注意您可以使用一些數學方法將線性索引更改為行和列。
for( int i = 0; i < totalElements; i++ ) {
int row = i / rowsCols;
int col = i % rowsCols;
matrix[row][col] = scanner.nextInt();
}
要使用逗號,您必須首先將掃描儀設置為使用空格或逗號作為分隔符。
scanner.useDelimiter( "[\\s,]+" );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.