好的,所以我在类里面有一个作业要编写一个返回二维数组中最大元素位置的方法。返回值是一个一维数组,包含两个元素,分别表示二维数组中最大元素所在的行和列。
public static void main(String[] args) {
int[] loc=new int[2];
Scanner scan=new Scanner(System.in);
int x,y;
System.out.print("Enter the size of your two-dimensional array. Length then height: ");
x=scan.nextInt();
y=scan.nextInt();
double [][]matrix=new double[x][y];
System.out.println("Enter your two-dimensional array row by column: ");
for (int i=0;i<y;i++){
for (int j=0;j<x;j++){
matrix[j][i]=scan.nextDouble();
System.out.print("i: "+i+" j: "+j + " ");
}
System.out.println();
}
System.out.println();
for (int i = 0; i<x; i++){
for (int j = 0; j<y; j++){
System.out.print(matrix[i][j] + ("i: "+i+" j: "+j + " "));
}
System.out.println();
}
loc=locateLargest(matrix,x,y);
System.out.println(matrix[loc[0]][loc[1]]);
}
public static int[] locateLargest(double[][] a ,int x, int y){
int m=0,n=0;
int[] location={0,0};
double largest=a[0][0];
for (int i=0;i<x;i++){
for (int j=0;j<y;j++){
System.out.println("X: "+i+" Y: "+j +" value: " + a[i][j]);
if (a[i][j]>largest){
location[0]=i;
m=i;
location[1]=j;
n=i;
}
}
}
System.out.println("the location of the largest element of you two-dimensional array is : (" + location[0] + ", " + location[1] + ")");
System.out.println(a[m][n]);
return location;
}
这是我的代码。它非常草率,可能没有多大意义。我包括了 main(String[] args) 和我的方法,因为两者都需要进行设置。当我运行它时,我得到了错误的答案,我试图通过打印出这些值来排除故障(我在我的代码中留下了这些打印行),我得到的答案是错误的。我相信这与我的数组元素的输入方式有关。
我使用的数组是 23.5 35 2 10 4.5 3 45 3.5 35 44 5.5 9.6 我一直得到的答案是 (2,2) 如果我没看错的话就是 5.5。 X的值为3,Y的值为4。
如能就我的代码返回错误答案的原因提供任何帮助,我们将不胜感激。谢谢。
编辑:我添加了 X 和 Y 的值。
最佳答案
在 block 中找到更大的值后,需要重新分配变量largest
:
if (a[i][j]>largest){
largest=a[i][j]; //current value is largest
location[0]=i;
location[1]=j;
}
删除变量m
和n
,它们是多余的。
关于java - 二维数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20561865/