[英]Transpose a 2d Array with varying dimensions in Java
嘿,我正在嘗試轉置2d數組,該數組的行/列由用戶輸入。 我在這個網站上四處張望,幾乎所有的建議都是關於方陣(2x2、3x3等)的。
這就是我到目前為止
import java.util.Scanner;
public class ArrayTranspose {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Input the number of rows (must be between 2 and 5): ");
int rows = kb.nextInt();
if ((rows < 2) && (rows > 5)) {
System.out.println("Error: range must be between 2-5");
rows = -1;
}
System.out.print("Input the number of columns (must be between 2 and 5): ");
int cols = kb.nextInt();
if ((cols < 2) && (cols > 5)) {
System.out.println("Error: range must be between 2-5");
cols = -1;
}
int myArray[][] = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.println("Enter a data value for (" + (i + 1) + ", " + (j + 1) + "): ");
int value = kb.nextInt();
myArray[i][j] = value;
}
}
printArray(myArray);
System.out.println();
int newArray[][] = transpose(myArray);
printNewArray(newArray);
}
public static void printArray(int myArray[][]) {
int dim1 = myArray.length; // Gets the number of rows
int dim2 = myArray[0].length; // Gets the number of columns
for (int i = 0; i < dim1; i++) {
for (int j = 0; j < dim2; j++) {
System.out.printf("%4d", myArray[i][j]);
}
System.out.println();
}
}
public static int[][] transpose(int myArray[][]) {
int newArray[][] = new int[myArray[0].length][myArray.length];
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < i; j++) {
// swap element[i,j] and element[j,i]
int temp = myArray[i][j];
newArray[i][j] = temp;
}
}
return newArray;
}
public static void printNewArray(int myArray[][]) {
int dim1 = myArray.length; // Gets the number of rows
int dim2 = myArray[0].length; // Gets the number of columns
for (int i = 0; i < dim1; i++) {
for (int j = 0; j < dim2; j++) {
System.out.printf("%4d", myArray[i][j]);
}
System.out.println();
}
}
}
當我運行程序時,我得到如下信息:
輸入行數(必須在2到5之間):2
輸入列數(必須在2到5之間):3
輸入(1,1)的數據值:
11
輸入(1,2)的數據值:
12
輸入(1,3)的數據值:
13
輸入(2,1)的數據值:
21
輸入(2,2)的數據值:
22
輸入(2,3)的數據值:
23
11 12 13
21 22 23
0 0
21 0
0 0
因此,看起來一切都進行得很好(它知道轉置數組的新維),但是轉置數組中的數據值並沒有吸收原始數組中的所有數字。
public static int[][] transpose(int myArray[][]) {
int newArray[][] = new int[myArray[0].length][myArray.length];
for (int i = 0; i < myArray[0].length; i++) {
for (int j = 0; j < myArray.length; j++) {
int temp = myArray[j][i];
newArray[i][j] = temp;
}
}
return newArray;
}
希望這可以幫助 :)
我只在這里簡化一點:
public static int[][] transpose(int myArray[][]) {
int newArray[][] = new int[myArray[0].length][myArray.length];
for (int i = 0; i < newArray.length; i++) {
for (int j = 0; j < newArray[i].length; j++) {
newArray[i][j] = myArray[j][i];
}
}
return newArray;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.