Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

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

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.

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'.

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.

Thank you for your time!

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

}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...