为了我的项目,我需要编写一个程序来输入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);
}
}