【问题标题】:How to make my java program print the smallest and largest numbers from the values i input如何让我的 java 程序从我输入的值中打印出最小和最大的数字
【发布时间】:2016-04-28 23:20:59
【问题描述】:

我需要 java 请求一个 int 类型的输入,然后立即打印出来并继续请求数字,直到输入一个哨兵告诉程序停止请求数字。一旦程序停止询问数字,我需要它打印出我输入的那组数字中的最小数字和最大数字,但是我不能使用数组或任何类似的东西,因为我需要制作一个方法来执行这个操作。我现在只做了2-3个月的java,所以我基本上是一个初学者。

【问题讨论】:

  • 是否有不能将数组传递给方法进行处理的原因?
  • 其实你可以将数组传递给函数我不知道你为什么说我不能使用数组?
  • 为什么需要一个数组来存储两个值? int min = Integer.MAX_VALUE; 然后int max = Integer.MIN_VALUE; 当你从用户那里得到输入时(比如n),然后max = Math.max(max, n)min = Math.min(min, n) 应该这样做。

标签: java algorithm numbers


【解决方案1】:

听起来像是家庭作业。所以不会给你确切的解决方案。但是你可以试试这样的:

 //declare two variables
 private static int max = 0;
 private static int min = 0;

现在在您的 main 方法中,当您继续输入整数时,您可以比较和替换值

  if (yourEnteredVariable > max){
      max =  yourEnteredVariable;
  }

  if (yourEnteredVariable < min){
     min =  yourEnteredVariable;
  }

您可以在单独的方法中使用上述子句。

【讨论】:

  • 我认为最好初始化max = Integer.MIN_VALUEmin = Integer.MAX_VALUE
猜你喜欢
  • 1970-01-01
  • 2018-07-08
  • 2018-03-08
  • 2012-10-09
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 2019-05-26
  • 2020-07-02
相关资源
最近更新 更多