【问题标题】:How to return different array values according to condition? [closed]如何根据条件返回不同的数组值? [关闭]
【发布时间】:2025-12-16 21:15:01
【问题描述】:

我正在尝试根据条件返回不同的数组值。这是我的代码,但它出错了。请帮我找出问题所在。

private static String subject[] = {"Mathematics", "English"};
private static String studentNum[] = {"1", "2"};
private static int marks[][] = {{56,51},   // Student 1 mark for Mathermatics
                                {69,85}};  // Student 2 mark for English

public static double AverageMarks(String aCode) {

    double sum[] = new double[subject.length];
    double average[] = new double[subject.length];

    for(int j=0;j<subject.length;j++) {
        for(int i=0;i<studentNum.length;i++) {
            sum[j] += marks[j][i];
            average[j] = (sum[j] / studentNum.length); // average[0] is the average mark of Mathermatics and average[1] is the average mark of English
        }

        if (aCode.equals(subject[j])) {
            return average[j];
        }
        else {
            return 0;
        }
    }    
}

【问题讨论】:

  • 您需要告诉我们有关错误的更多详细信息

标签: java arrays return


【解决方案1】:

你快到了。线

average[j] = (sum[j] / studentNum.length);

应该在嵌套的for之外,因为嵌套的for用于对每个成绩求和,完成后你应该将总和分配给sum[j]

另外,你应该把return 0放在函数的末尾,否则for循环只会循环一次(因为如果条件aCode.equals(...)不成立,它将return 0)在第一个循环。

public static double averageMarks(String aCode)
{
    double sum[] = new double[subject.length];
    double average[] = new double[subject.length];

    for (int j = 0; j < subject.length; j++) {
        for (int i = 0; i < studentNum.length; i++) {
            sum[j] += marks[j][i];

        }
        average[j] = (sum[j] / studentNum.length); // average[0] is the average mark of Mathermatics and average[1] is the average mark of English

        if (aCode.equals(subject[j])) {
            return average[j];
        }
    }
    return 0;
}

注意:我建议您遵循 Java 命名约定。你的方法应该被称为methodName,而不是MethodName

【讨论】:

    【解决方案2】:

    您的程序中有死代码。

    for(int j=0;j<subject.length;j++)
    

    这些loop 没有用,因为在循环的第一次迭代中您使用的是return

    还缺少一个return 类型的方法,它必须在两个循环之外。

    【讨论】:

      【解决方案3】:

      我最初的样子,我注意到了这一点,因为你没有描述更多关于你的错误我布局我看到的第一件事可能是错误的。

      if (aCode.equals(subject[j])) {return average[j];}
          else {return 0;}
      

      我认为这行代码是错误的。它永远不会到达外部循环来检查不同的主题,因为它直接进入else.

      public static double AverageMarks(String aCode) {
      
          double sum[] = new double[subject.length];
          double average[] = new double[subject.length];
      
          for(int j=0;j<subject.length;j++){
              for(int i=0;i<studentNum.length;i++) {
                  sum[j] += marks[j][i];
               }
              average[j] = (sum[j] / studentNum.length);
              if (aCode.equals(subject[j])) return average[j];
          }
          return 0;
      }
      

      【讨论】: