【问题标题】:How can I locate and print the index of a max value in an array?如何定位和打印数组中最大值的索引?
【发布时间】:2012-02-17 22:50:33
【问题描述】:

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

}
}

【问题讨论】:

    标签: java arrays for-loop


    【解决方案1】:

    您可以将最后一部分更改为:

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

    【讨论】:

      【解决方案2】:

      您的错误在于比较 if ((newnumber &gt; modetracker[i-1])。您应该检查newnumber 是否大于已经找到的最大值。那是if ((newnumber &gt; 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);
      

      【讨论】:

      • 对于带作业标记的问题,更合适的做法是指出 Op 的工作出了什么问题,而不是提供逐字逐句的解决方案
      • 好的,谢谢-我按照代码并理解它。谢谢!
      猜你喜欢
      • 2020-09-19
      • 1970-01-01
      • 2014-12-27
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 2013-01-11
      • 2019-08-21
      • 1970-01-01
      相关资源
      最近更新 更多