Location of Largest Number in an Array

2019-09-11 11:18发布

问题:

My program is supposed to prompt the user to input the number of rows and columns in an array and then input the array. The location of the largest element in the array is then calculated and displays.

My code keeps displaying (0,1) instead of the actual result, (1,2). Any ideas?

My code:

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;
    }
}

Result:

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)

EDIT

I had:

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

at line 32, but this error kept coming up:

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

at Question8_13.locateLargest(Question8_13.java:33)

at Question8_13.main(Question8_13.java:21)

Java Result: 1"

The only way I can get the program to actually run and that error to not come up is by only checking for row = 0

回答1:

In your loop:

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

The number of rows is a.length, not a[0].length. a[0].length is the number of columns in the first row.



回答2:

Replace your for-loop with something like this:

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;
         }
     }
 }

You were only checking the first row. Now you are iterating over each column for each row.