【问题标题】:How to find minimum and maximum of the numbers you input without arrays ? (simple)如何在没有数组的情况下找到您输入的数字的最小值和最大值? (简单的)
【发布时间】:2020-03-02 12:07:41
【问题描述】:

我有这个任务,但我被卡住了,请帮忙,我相信它会很快。请帮忙!

这是我的提示: 编写一个方法 minMax( ),它有一个 int 类型参数,表示你想输入多少个整数。它将输入那么多整数,并打印输入值中的最小值和最大值。

minMax(5) 将输入 5 个整数值并打印输入值的最小值和最大值。

我尝试检查与我的主题相关的问题,但是它们太复杂了。这是简单的代码。

import java.io.*;
import java.util.*;

public class Main {
  public static void main(String[] args) {
    //call your method here 

   }
  public static int minMax(int num){
   Scanner scan = new Scanner(System.in);
   System.out.println("Enter a value: ");
   int num = scan.nextInt();
   int min = num;
   int max = num;
   for(int i = 1; i < ; i++){

    }
  }
}

【问题讨论】:

  • 这个问题似乎根本没有包括任何解决问题的尝试。请编辑问题以显示您尝试过的内容,并使用Minimal, Complete, and Verifiable example 显示您遇到的特定障碍。欲了解更多信息,请参阅How to Ask
  • 将每个输入与预先存在的结果进行比较
  • 提示一:不要在你的方法中重新定义num。提示二:制作方法voidint 你会回来吗?提示三:初始化minInteger.MAX_VALUEmaxInteger.MIN_VALUE 提示四:for (int i = 0; i &lt; num; i++)

标签: java max java.util.scanner min


【解决方案1】:

这是为您提供的快速解决方案。

请检查以下代码以从所有元素列表中获取最小值和最大值。

输入:

请输入 N 的值: 5

请输入5个数字

4

2

10

156

2

输出:

N 个数的最大值为:156

N 个数的最小值为:2

public static void main(String arg[]) {
        Scanner scan = null;
        int n = 0;
        int max = 0,min = 0;
        try {
            System.out.println("Please enter value of N: ");
            scan = new Scanner(System.in);
            n = scan.nextInt();
            max = Integer.MIN_VALUE;
            min = Integer.MAX_VALUE;
            System.out.printf("Please enter %d numbers %n", n);
            for (int i = 0; i < n; i++) {
                int current = scan.nextInt();
                if (current > max) {
                    max = current;
                }
                if (current < min) {
                    min = current;
                }
            }
            System.out.println("Max of N number is : " + max);
            System.out.println("Min of N number is : " + min);
        }
        catch (Exception ex) {
                ex.printStackTrace();
        }finally{
                scan.close();
        }
    }

希望此解决方案有效。

如果此解决方案有帮助,请标记为答案。

【讨论】:

  • 这个答案与我之前看到的类似。有没有更简单的说法?我还提到过没有使用数组。
猜你喜欢
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 1970-01-01
  • 2018-03-18
相关资源
最近更新 更多