[英]Square matrices
我需要編寫一個程序,當用戶輸入行和列時,它應該輸出以下內容。 以下示例適用於 4x4 矩陣:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
仍然是初學者,發現這些數組真的很難。
它適用於下面的代碼,但我不確定是否允許像這樣填充 - 列然后是行。
我無法找到一種方法來處理:
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
我使用的代碼:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your array rows: ");
int rows = scanner.nextInt();
System.out.println("Please enter your array columns: ");
int columns = scanner.nextInt();
int[][] array = new int[rows][columns];
int counter = 0;
for (int j = 0; j < columns; j++){
for (int i = 0; i < rows; i++) {
counter++;
array[i][j]=counter;
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
您要在此處使用的技巧是使用函數來計算給定單元格的值。 該功能相對容易......對於每一行,值隨着行數增加。 例如有 4 行,所以每行的值增加 4..... 1, 5, 9, 13, ....
因此,您的代碼可以簡化為:
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
System.out.print((r + 1 + (c * rows)) + " ");
}
System.out.println();
}
不需要任何陣列或臨時存儲等。
重申一下,每個單元格的值是行(從索引 1 開始,而不是 0)加上基於列號(從 0 開始)的“偏移量”。
你可以看到它在這里運行: http : //ideone.com/RqPgbN
按照您的方式填充數組沒有問題,這是完全合法的。 以行為先填充它不會產生任何真正的區別。
如果您真的希望以行為先,以下是一種方法:
int[][] array = new int[rows][columns];
for(int i = 0; i < rows, i++) {
for(int j = 0; j < columns; j++) {
array[i][j] = j * rows + i + 1;
}
}
試試這個代碼:-
int counter = 0;
for (int j = 0; j < rows; j++){
for (int i = 0; i < columns; i++) {
int temp = scanner.nextInt();
array[i][j]=temp;
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(array[i][j] + "\t");
}
System.out.println();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.