【问题标题】:Find and Print high number array method Java查找和打印高数数组方法Java
【发布时间】:2012-12-06 12:04:57
【问题描述】:

我正在尝试做的是搜索“gradePsd”数组找到最高成绩,如果有两个成绩相同,则打印学生的姓名以进行控制台。

我遇到的问题是这个方法正在获取数组的第一个索引值并打印它,因为它是第一遍的高值,如果第二个值大于第一个值,那么它也会打印等等。

所以我的问题是我怎样才能让它打印出高分的学生。

public static void hiMarkMethod(String[] NamePsd, int[] gradePsd)
{
    String nameRtn = "";
    int num = gradePsd[0];

    System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:");

    for (int  i = 0; i < gradePsd.length;  i++)
    {
        if (gradePsd[i] >= num)
        {
            num = gradePsd[i];
            nameRtn = NamePsd[i]; 
        }

        System.out.print(nameRtn + ", ");
    }
}

【问题讨论】:

    标签: java arrays methods numbers find


    【解决方案1】:

    首先找到最大的数字 然后用那个号码打印学生

    public static void hiMarkMethod(String[] NamePsd, int[] gradePsd)
        {
    
        String nameRtn = "";
        int num = gradePsd[0];
    
         System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:");
        //find the highest number
        for (int  i = 0; i < gradePsd.length;  i++){
        if (gradePsd[i] >= num){
            num = gradePsd[i];
        }
        //print students with that number
        for (int  j = 0; j < NamePsd.length;  j++){
            if (gradePsd[j] == num)
            {
                nameRtn = NamePsd[j]; 
                System.out.print(nameRtn + ", "); 
            }
        }
    

    可能的 1000 个解决方案之一。

    【讨论】:

      【解决方案2】:

      使用 -1 初始化 num 并将 System.out 从 for 循环中取出。但是您只能使用您的代码确定一名学生。如果您想存储多个名称,则需要将 nameRtn 设为 Collection

      类似这样的:

      public static void hiMarkMethod(String[] NamePsd, int[] gradePsd) {
          Collection<String> namesRtn = new ArrayList<String>();
          int num = -1;
      
          for (int  i = 0; i < gradePsd.length;  i++) {
              if (gradePsd[i] > num) {
                  num = gradePsd[i];
                  namesRtn.clear();  // clear name list as we have a new highest grade
                  namesRtn.add(NamePsd[i]);  // store name in list
              } else if (gradePsd[i] == num) {
                  namesRtn.add(NamePsd[i]);  // if a second student has the same grade store it to the list
              }
      
          }
          System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are: " + namesRtn);
      }
      

      【讨论】:

        猜你喜欢
        • 2021-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-23
        • 1970-01-01
        • 2016-11-17
        • 1970-01-01
        • 2013-03-24
        相关资源
        最近更新 更多