How can I locate and print the index of a max value in an array?

前端 未结 2 2091
遇见更好的自我
遇见更好的自我 2020-12-11 03:09

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 arr

相关标签:
2条回答
  • 2020-12-11 03:58

    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);
    
    0 讨论(0)
  • 2020-12-11 04:01

    You could change last part to:

    int maxIndex = 0;
    for (int i = 0; i < modetracker.length; i++) {
        if (modetracker[i] > max) {
            max = modetracker[i];
            maxIndex = i;
        }
    }
    System.out.println(maxIndex);
    
    0 讨论(0)
提交回复
热议问题