【问题标题】:Location of Largest Number in an Array数组中最大数的位置
【发布时间】:2015-09-18 19:57:00
【问题描述】:

我的程序应该提示用户输入数组中的行数和列数,然后输入数组。然后计算并显示数组中最大元素的位置。

我的代码一直显示 (0,1) 而不是实际结果 (1,2)。有什么想法吗?

我的代码:

import java.util.Scanner;

public class Question8_13 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of rows and columns in the array: ");
        int row = input.nextInt();
        int col = input.nextInt();
        System.out.println("Enter numbers into array: ");
        double[][] a = new double[row][col];
        for (double[] a1 : a) {
            for (int j = 0; j < a1.length; j++) {
                a1[j] = input.nextDouble();
            }
        }
        int[] largest = locateLargest(a);
        System.out.println("The location of the largest element is at: (" +  largest[0] + "," + largest[1] + ")");
        for (int i = 0; i < 2; i++) {
            System.out.print(largest[i]);
        }
    }

    public static int[] locateLargest(double[][] a) {
        double max = 0;
        int maxRow = 0;
        int maxColumn = 0;
        int row = 0;
        for (int column = 0; column < a[row].length; column++) {
            if (a[row][column] > max) {
                max = a[row][column];
                maxRow = row;
                maxColumn = column;
            }
        }
        int[] largest = new int[2];
        largest[0] = maxRow;
        largest[1] = maxColumn;
        return largest;
    }
}

结果:

Enter the number of rows and columns in the array: 3 4

Enter numbers into array: 

23.5 35 2 10

4.5 3 45 3.5

35 44 5.5 9.6

The location of the largest element is at: (0,1)

编辑

我有:

for (int row = 0; row

在第 32 行,但此错误不断出现:

“线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:3

at Question8_13.locateLargest(Question8_13.java:33)

at Question8_13.main(Question8_13.java:21)

Java 结果:1"

我可以让程序实际运行并且不会出现错误的唯一方法是仅检查 row = 0

【问题讨论】:

  • 除了0 之外,您还在哪里检查行?您是否尝试使用调试器调试此代码?
  • 因为您只检查 row = 0,所以您的 locateLargest() 方法中还应该有另一个 for 循环。
  • 在原帖中进行了编辑
  • 更新原始问题中的代码。阅读未格式化的代码并不好玩,而且会使 cmets 变得混乱。
  • 已经这样做了。我是这个网站的新手,直到我发布它之后才意识到评论部分的结果。

标签: java arrays numbers 2d


【解决方案1】:

在你的循环中:

for (int row = 0; row < a[0].length; row++)

行数是a.length,而不是a[0].length。 a[0].length 是第一行的列数。

【讨论】:

    【解决方案2】:

    用这样的东西替换你的for循环:

    for (int i = 0; i < a.length; i++) {
         for (int j = 0; j < a[i].length; j++) {
             if (a[i][j] > max) {
                 max = a[i][j];
                 maxRow = i;
                 maxColumn = j;
             }
         }
     }
    

    您只检查了第一行。现在您正在迭代每一行的每一列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-06
      • 2021-11-17
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-04
      相关资源
      最近更新 更多