如何在数组中找到并打印最大值的索引?

梨子:

对于我的项目,我需要制作一个程序以10个数字作为输入并显示这些数字的模式。该程序应使用两个数组和一个将数字数组作为参数并在数组中返回最大值的方法。

基本上,到目前为止,我所做的是使用第二个数组来跟踪一个数字出现了多少次。查看初始数组,您将看到模式为4。(显示最多的数字)。在第二个数组中,索引4的值为2,因此2将是第二个数组中的最大值。我需要在第二个数组中找到该最大值,然后打印索引。我的输出应为“ 4”。

在尝试生成“ 4”之前,我的程序一直运行良好,并且尝试了一些不同的操作,但似乎无法使其正常工作。

感谢您的时间!

public class arrayProject {

public static void main(String[] args) {
    int[] arraytwo = {0, 1, 2, 3, 4, 4, 6, 7, 8, 9};
    projecttwo(arraytwo);
}


public static void projecttwo(int[]array){
    /*Program that takes 10 numbers as input and displays the mode of these numbers. Program should use parallel
     arrays and a method that takes array of numbers as parameter and returns max value in array*/
    int modetracker[] = new int[10];
    int max = 0; int number = 0;
    for (int i = 0; i < array.length; i++){
        modetracker[array[i]] += 1;     //Add one to each index of modetracker where the element of array[i] appears.
    }

    int index = 0;
    for (int i = 1; i < modetracker.length; i++){
        int newnumber = modetracker[i];
        if ((newnumber > modetracker[i-1]) == true){
            index = i;
        }
    } System.out.println(+index);

}
}
伊萨:

您的错误在于比较if ((newnumber > modetracker[i-1])您应该检查是否newnumber大于已找到的最大值。那是if ((newnumber > modetracker[maxIndex])

您应将最后一行更改为:

    int maxIndex = 0;
    for (int i = 1; i < modetracker.length; i++) {
        int newnumber = modetracker[i];
        if ((newnumber > modetracker[maxIndex])) {
            maxIndex = i;
        }
    }
    System.out.println(maxIndex);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在数组中找到最大值

如何在数组中找到最大值和最小值

如何在向量列中找到最大值的索引?

如何在 Python 的列表中找到最大值的索引?

如何在整个带有索引的2D数组中找到最大值

如何在二维数组(矩阵)中找到局部最大值的索引?

如何在MongoDB中缺少字段的数组中找到最大值的索引?

如何在Swift对象数组中找到最大值?

如何在教堂中找到数组的最大值

如何在dataframe列的数组中找到最大值?

如何在numpy数组列中找到最大值?

如何在多维数组中找到最大值

如何在numpy数组中找到对应的最大值

如何在列表中找到数组的最大值?

如何在不使用if语句的情况下在数组中找到最大值和最小值?

如何在数组以及对应的日期中找到最大值和最小值

如何在多个数组中找到最大值并返回java中第一个索引的值?

如何找到数组最大值的索引?

快速数组中找到最大值的索引

如何在存储在数据框中的多个列表中找到最大值?

如何在数据存储区中找到最大值?

如何在Perl 6中的列表中找到最大值的索引?

如何在julialang中找到最后一个最大值的索引?

如何在熊猫数据框中找到两个索引之间的最大值

如何在二维列表的一行中找到最大值及其索引?

如何在 numpy 數組中找到行索引的最大值?

如何在 Python 中找到二维数组的最小值和最大值

如何在整个二维数组中找到最大值(处理)

如何在MATLAB中找到多个数组的最大值?