【问题标题】:getting max and min of five input from user more than one time不止一次地从用户那里获得五个输入的最大值和最小值
【发布时间】:2018-11-20 20:30:46
【问题描述】:
package com.company;

import java.util.Scanner;

class Compare
{
    Integer max;
    Integer min;

    public void max(int num)
    {
        if (max == null)
            max = num;
        else if(num > max)
            max = num;
    }

    public void min(int num)
    {
        if (min == null)
            min = num;
        else if(num < min)
            min = num;
    }
}
class Main
{
    public static void main(String args[])
    {
        Compare compare = new Compare();
        Scanner input = new Scanner(System.in);

        int sets = input.nextInt();
        for (int i = 0; i < sets ; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                int num_main = input.nextInt();
                compare.max(num_main);
                compare.min(num_main);
            }
            System.out.println(compare.max);
            System.out.println(compare.min);
        }
    }
}

我想计算来自用户的五个输入的最大值和最小值,我设法得到最大值和最小值,但是如果我测试两个组,我没有得到正确的最大值,而是我将前一个最大值作为我的最大值价值。我怎样才能以最简单的方式获得最大值

【问题讨论】:

  • 想想infinite loops 和导致它终止的条件。

标签: java class methods max min


【解决方案1】:

最小的变化是将compare 移动到第一个循环中,因此每次输入新的“set”数字时,它都会找到新的max(和min)。

for (int i = 0; i < sets ; i++)
{
    Compare compare = new Compare();
    //...
    //as you were     
}

当您在此循环之前创建compare 时,它将保留输入的每组数字的值。 您希望它找到maxmin 组输入的数字。

【讨论】:

    【解决方案2】:

    在移动到下一个循环之前,您必须恢复您的 compare 对象。在您的代码中稍作修改:

     for (int i = 0; i < sets ; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                int num_main = input.nextInt();
                compare.max(num_main);
                compare.min(num_main);
            }
            System.out.println(compare.max);
            System.out.println(compare.min);
            compare = new Compare();
        }
    

    说明: 假设sets = 2: 在获得 5 个用户输入后,您将获得最大值和最小值。在移动到第二个循环之前,您必须在获得 5 个下一个用户输入之前恢复您的 compare 对象,如上述代码。你也可以这样做:

    for (int i = 0; i < sets ; i++)
    {
        for (int j = 0; j < 5; j++)
        {
            int num_main = input.nextInt();
            compare.max(num_main);
            compare.min(num_main);
        }
        System.out.println(compare.max);
        System.out.println(compare.min);
        compare.max = compare.min = null;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 2014-12-31
      • 1970-01-01
      • 1970-01-01
      • 2013-11-12
      • 2016-10-12
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      相关资源
      最近更新 更多