【问题标题】:Return type error?返回类型错误?
【发布时间】:2014-11-12 03:17:51
【问题描述】:

我正在为我的班级做 Java 练习并遇到错误。它说“不兼容的类型:意外的返回值”。如果有人可以检查我是否正确执行此代码也会很好。我的指示是创建一个要初始化为第一个元素的变量 maxValue。然后我必须将 maxValue 存储的元素与列表中的另一个元素进行比较。如果数组中的某个元素大于 maxValue 中存储的元素,则假设使用较大的元素存储/更新 maxValue。

public class MyArray
  {
   public static void main(String[] args)
   {
   int[] ArrayLargestElement = {
       45, 38, 27, 
       46, 81, 72,
       56, 61, 20,
       48, 76, 91, 
       57, 35, 78
    };
   int maxValue = ArrayLargestElement[0]
   for (int i=0; i<ArrayLargestElement.length; i++) {
       if (maxValue  > ArrayLargestElement[i]) {
           maxValue = ArrayLargestElement[i];
        }
   }
   return maxValue;    
  } 
}

【问题讨论】:

  • public static void main() 没有返回值!
  • 为什么要从 main() 中返回值?

标签: java types return


【解决方案1】:

main() 是静态无效的。它无法返回maxValue。我想你想print它。

// return maxValue;    
System.out.printf("maxValue = %d%n", maxValue);

但也许您正试图将其提取到类似的方法中

public static int getLargestValue(int[] arr) {
    if (arr == null) {
        return Integer.MIN_VALUE;
    }
    int max = arr[0];
    for (int i = 1; i < arr.length; i++) {
        max = Integer.max(max, arr[i]);
    }
    return max;
}

然后你可以在main() 中调用它

public static int getLargestValue(int[] arr) {
    if (arr == null) {
        return Integer.MIN_VALUE;
    }
    int max = arr[0];
    for (int i = 1; i < arr.length; i++) {
        max = Integer.max(max, arr[i]);
    }
    return max;
}

public static void main(String[] args) {
    int[] array = { 45, 38, 27, 46, 81, 72, 56, 61, 20, 48, 76, 91, 57, 35,
            78 };
    System.out.println(getLargestValue(array));
}

【讨论】:

    【解决方案2】:

    您不能在void Main() 函数中返回值。 编写函数返回一个值。

    public static int getmax(int max[])
       {
           int maxValue = max[0]
       for (int i=0; i<max.length; i++) 
        {
       if (maxValue  > max[i]) 
          {
           maxValue = max[i];
          }
        }
       return maxValue; 
      } 
    

    调用main中的函数

    public class MyArray
      {
       public static void main(String[] args)
        {
         int[] ArrayLargestElement = {
          45, 38, 27, 
          46, 81, 72,
          56, 61, 20,
          48, 76, 91, 
          57, 35, 78
         };
         System.out.print("Maximum value in ArrayList"+getmax(ArrayLargestElement));
      }
         /*write your function here */
    }
    

    【讨论】:

    • main(),你的意思是?案件很重要。
    【解决方案3】:

    main() 本质上是一个 void 方法。它并不意味着返回一个值。但是,您可以使用 System.out.println 将您的 maxValue 显示到控制台。否则,我建议编写一个实际上会为您返回最大值的方法,就像上面列出的方法之一。希望这有帮助!

    【讨论】:

      猜你喜欢
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-08
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 2019-12-12
      相关资源
      最近更新 更多