最大号的位置在一个数组 [英] Location of Largest Number in an Array

查看:253
本文介绍了最大号的位置在一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我的code继续显示(0,1),而不是实际的结果,(1,2)。任何想法?

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

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


结果:

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)


修改

我有:

有关(INT行= 0;行&LT; A [0] .length;排++){

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

在第32行,但这个错误不停地来了:

at line 32, but this error kept coming up:

在线程异常主要java.lang.ArrayIndexOutOfBoundsException:3

"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结果:1

Java Result: 1"

我可以得到程序实际运行不上来的唯一途径,该错误是只检查行= 0

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

推荐答案

在你的循环:

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

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

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

这篇关于最大号的位置在一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆