如何定位并打印数组中最大值的索引? [英] How can I locate and print the index of a max value in an array?

查看:32
本文介绍了如何定位并打印数组中最大值的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For my project, I need to make a program that takes 10 numbers as input and displays the mode of these numbers. The program should use two arrays and a method that takes array of numbers as parameter and returns max value in array.

基本上,到目前为止我所做的是使用第二个数组来跟踪数字出现的次数.查看初始数组,您将看到众数为 4.(出现最多的数字).在第二个数组中,索引 4 的值为 2,因此 2 将是第二个数组中的最大值.我需要在我的第二个数组中找到这个最大值,并打印索引.我的输出应该是'4'.

Basically, what I've done so far is used a second array to keep track of how many times a number appears. Looking at the initial array, you will see that the mode is 4. (Number that appears most). In the second array, the index 4 will have a value of 2, and thus 2 will be the maximum value in the second array. I need to locate this max value in my second array, and print the index. My output should be '4'.

在我尝试生成4"之前,我的程序一直很好,而且我尝试了一些不同的方法,但似乎无法正常工作.

My program is good up until I attempt to produce the '4', and I've tried a few different things but can't seem to get it to work properly.

感谢您的宝贵时间!

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])

Your mistake is in comparing if ((newnumber > modetracker[i-1]). You should check if the newnumber is bigger then the already found max. That is if ((newnumber > modetracker[maxIndex])

您应该将最后一行更改为:

You should change your last rows to:

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

这篇关于如何定位并打印数组中最大值的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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