【发布时间】:2015-07-01 21:20:27
【问题描述】:
创建二维数组说 m :
- 要求用户从键盘输入行和列的大小(使用扫描仪)。 N IS 9,如果用户输入的列大小大于 N+4,则要求用户重新输入列大小
- 使用随机对象将所有数组元素填充为 (3.0 , 13.0) 范围内的双精度数
-
传递上面的数组m,调用下面两个方法
- 在
findMaxRow(double[][]array)中,查找并打印二维数组中最大的列总和 - 在
returnAvg(m)中,打印出数组m的平均值
- 在
评论:
所以,我编写了代码来查找最大 Colm,但我不知道如何找到最大行。我需要能够找到最大行,但我正在弄清楚如何找到,因为我的代码找到了 cllm 而不是最大行。
这是我的代码:import java.util.Scanner;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
System.out.print("Number of Rows? ");
int rows = input.nextInt();
System.out.print("Number of Columns? ");
int columns = input.nextInt();
while (columns > 7) { // check for column > n+5 where n = 2 in my case
System.out.print("The column amount is too high. Try another number: ");
columns = input.nextInt();
}
double[][] m = new double[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
m[i][j] = rand.nextDouble()*7+4;
}
}
findMaxCol(m);
System.out.println("The average value of this array is "+returnAvg(m));
}
public static void findMaxCol(double[][] a) {
double[] maxCol = new double[a[0].length];
double max = 0;
int maxColNum=0;
for (int i = 0; i < a[0].length; i++) { // Sum of Columns
for (int j = 0; j < a.length; j++) {
maxCol[i]+=a[j][i];
}
}
//System.out.println(Arrays.toString(maxCol));
for (int i = 0; i < maxCol.length; i++) {
if (max < maxCol[i]) {
max = maxCol[i];
maxColNum = i; // column number will associate with its array column starting with 0
}
}
System.out.println("The highest column sum is Column #"+maxColNum+" with a sum of "+max);
}
public static double returnAvg(double[][] a) {
double sum = 0; // initialization
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
sum+=a[i][j];
}
}
// System.out.println(sum); Test line
return (sum/(a.length*a[0].length)); // avg
}
}
【问题讨论】:
-
列和行只是我们用来建模数据的很好的抽象;它们实际上并不是二维数组本身的固有方面。您能否澄清您的具体要求并将您的代码示例压缩为MCVE?
-
我的代码只找到我希望它找到行的最大列。我怎么能做到这一点。我是 java 新手,可以使用帮助。
-
你没有把我刚才说的话考虑进去。
-
您能详细说明一下吗?
-
这就是我需要它做的事情
标签: java arrays multidimensional-array