【问题标题】:How can I get the max value of this array to print?我怎样才能得到这个数组的最大值来打印?
【发布时间】:2019-06-01 14:30:52
【问题描述】:

我正在练习使用数组,我现在只想打印这个数组的最大值,但我无法弄清楚,我已经尝试过查看所有内容。请有人解释一下。

import java.util.*;

class Practice
{
   public static void main(String[] args)
   {
      int[] Array = {5, 7, 2, 10};
   }

      public static int getMaxValue(int[] Array)
      {
         int maxValue = Array[0];

         for (int i = 1; i < Array.length; i++)
         {
            if (Array[i] > maxValue) 
            {
                maxValue = Array[i];
            } 
         }
         return maxValue;
      } 
} 

它编译没有错误,但不打印最大值。

【问题讨论】:

  • 为什么你认为它应该打印任何东西?
  • 你似乎从来没有给getMaxValue打电话,或者在任何地方打印出来。
  • 一切正常 ;) ...你只是忘了打电话给getMaxValue。只需将int[] Array = {5, 7, 2, 10}; 替换为System.out.printf("%s", getMaxValue(new int[] {5, 7, 2, 10}));
  • 旁注:您找到最大值的代码不正确。数组从 0 开始计数,因此您通过在 1 处开始 for 循环来跳过第一个值
  • 不是——第一个值是在循环上方读取的。

标签: java arrays output max min


【解决方案1】:

您的代码有效,您只需要打印方法的输出:

class Main {
    public static void main(String[] args) {
        int[] Array = {5, 7, 2, 10};
        System.out.println(getMaxValue(Array));
    }

    public static int getMaxValue(int[] Array) {
        int maxValue = Array[0];

        for (int i = 1; i < Array.length; i++) {
            if (Array[i] > maxValue) {
                maxValue = Array[i];
            }
        }
        return maxValue;
    }
}

【讨论】:

    【解决方案2】:

    你忘了调用函数

       public static void main(String[] args)
       {
          int[] array = {5, 7, 2, 10};
    
          // call getMaxValue method and print the returned value
          System.out.println(getMaxValue(array));
       }
    

    结果:

    10
    

    【讨论】:

      【解决方案3】:

      通过以下方式简单地打印您的控制台,并基于 Java 代码约定为您的案例数组中的变量小写:

      import java.util.*;
      
      public class Practice
      {
         public static void main(String[] args)
         {
            int[] array = {5, 7, 2, 10};
            System.out.println(getMaxValue(array)); 
         }
      
         public static int getMaxValue(int[] array)
         {
           int maxValue = array[0];
      
           for (int i = 1; i < array.length; i++)
           {
              if (array[i] > maxValue) 
              {
                  maxValue = array[i];
              } 
           }
           return maxValue;
        } 
      } 
      

      【讨论】:

        【解决方案4】:

        在练习数组时,您可能希望使用 Java 流,如下所示:

        public static void main(String[] args) {
            int[] array = {5, 7, 2, 10};
            Integer max = IntStream.of(array).max().orElseThrow(null);
            System.out.println(max);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-11-03
          • 2011-04-11
          • 1970-01-01
          • 1970-01-01
          • 2022-01-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多