我试图做一个2D数组程序来演示TRANSPOSE但我收到错误..这是我的代码。
import java.util.Scanner;
/* To demonstrate TRANSPOSE USING 2-D array */
public class Array_2ddd {
public static void main(String args[]) {
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[9][9];
int myArray2[][] = new int[9][9];
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.println("Enter array from 1 to 9");
myArray1[i][j] = s1.nextInt();
System.out.print("your array is" + myArray2[i][j]);
}
}
// Transposing now...
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.print("Your array is as follow" + myArray2[i][j]);
}
}
}
}
答案 0 :(得分:0)
您将矩阵定义为9x9
int myArray1[][] = new int[9][9];
但实际上你想插入10x10项:
for (i = 0; i <= 9; i++)
{
for (j = 0; j <= 9; j++)
所以:
重新定义数组以存储10x10项
int myArray1 [] [] = new int [10] [10];
仅在已定义的数组中读取和存储9x9项目
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++)
答案 1 :(得分:0)
您没有关闭第一个外部for循环,即第17行,并将数组大小更改为10,因为您需要输入10个输入(0到9 = 10个值)。
答案 2 :(得分:0)
您的代码中存在多个错误,建议将数组的维度声明为final int,因此您的代码适用于所有矩阵大小,并且调试更容易。在原始代码中,错误是:
myArray[2]
的一个元素。这意味着,您将获得your array is0
。System.out.print("Your array is as follow" + myArray2[i][j]);
,并且忘记在每行之后添加新行(当内循环完成时)。i,j
索引。你可能误认为一个带有长但终止循环的无限循环。你的转置步骤很好。
这是您的代码的精炼版本,允许您输入数组(按阅读顺序,或者更专业地,行主要顺序),创建转置数组。您可以直接使用此代码复制和比较当前代码以进行测试。
public static void main(String args[]) {
final int m = 9; // Rows
final int n = 9; // Columns
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[m][n]; // Original array, m rows n cols
int myArray2[][] = new int[n][m]; // Transposed array, n rows m cols
// Input
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
// Should be only prompt.
// Improved to show which entry will be affected.
System.out.printf("[%d][%d]" + "Enter array from 1 to 9\n", i, j);
myArray1[i][j] = s1.nextInt();
}
}
// Transposing now (watch for the ordering of m, n in loops)...
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing, output
System.out.print("Your array is:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
System.out.print(myArray1[i][j] + " ");
}
System.out.println(); // New line after row is finished
}
System.out.print("Your transposed array is:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.print(myArray2[i][j] + " ");
}
System.out.println();
}
s1.close();
}
对于有三行(m = 3)和四列(n = 4)的数组,我输入的数字从0到9,然后是0,1,2。正如预期的那样,输出应该是:
Your array is:
0 1 2 3
4 5 6 7
8 9 0 1
Your transposed array is:
0 4 8
1 5 9
2 6 0
3 7 1