嘿我试图转置用户输入的行/列的二维数组。我在这个网站上四处看看,我看到的所有建议都是方阵(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
所以看起来一切进展顺利(它知道转置数组的新维度)但是转置数组中的数据值不会占用原始数组中的所有数字。
答案 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;
}
希望这有助于:)
答案 1 :(得分:0)
我只在这个地方做了一点简单:
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;
}