【问题标题】:I can't find max and min我找不到最大值和最小值
【发布时间】:2015-03-09 20:16:24
【问题描述】:

我想创建一个程序,从用户那里读取超过 10 个数字并找到最大数字和最小数字,然后打印来自用户的所有数字。

这是我的程序,但我不知道如何找到最大数和最小数:

import java.io.*;

public class ass3 {
    public static void main (String [] args) throws IOException
    {
        int times , num1 ;
        int max , min;
        System.out.print("How many numbers you want to enter?\n*moer than five number");
        times=IOClass.getInt();
        if (times>5) {
           for(int i = 0;i<times;i++){
              System.out.println("please type the "+i+ "number");
              num1=IOClass.getInt();
           }
        }           
    }
}

【问题讨论】:

  • 如果您不将数字存储在任何地方,将很难全部显示出来。

标签: java database performance data-structures


【解决方案1】:

如果你像这样初始化minmax

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

您可以检查新数字是否小于min 或大于max,并根据需要进行更改:

int num = ...;
if (num < min) {
    min = num;
}
if (num > max) {
    max = num;
}

【讨论】:

    【解决方案2】:

    这是我的解决方案,希望对您有所帮助:

    import java.util.Scanner;
    
    public class Test 
    {
    
        public static void main(String[] args) 
        {       
            Scanner in = new Scanner(System.in);
            System.out.print("How many numbers you want to enter?\nThe number must be grater than 5");
            int times = in.nextInt();
            if (times > 5)
            {
                int[] numbers = new int[times];
                int min = Integer.MAX_VALUE; 
                int max = Integer.MIN_VALUE;
                for(int i = 0; i < times; i++)
                {
                    System.out.println("Please type the " + i + " number:");
                    int number = in.nextInt();
                    numbers[i] = number;
                    if(number < min)
                    {
                        min = number;
                    }
                    if(number > max)
                    {
                        max = number;
                    }
                }
                System.out.println("Max: " + max);
                System.out.println("Min: " + min);
            }
            in.close();
        }
    }
    

    【讨论】:

    • 嗯,你能解释一下这里的一切吗?我的意思是告诉我每行的用处是什么。以及如何找到总数:(
    • 当然!所以Scanner in = new Scanner(System.in) 用于控制台/终端中的用户输入。每次您想获得一个号码时,您都使用in.nextInt(),其中 - in - 是扫描仪的名称。因为您现在想要存储所有数字的最小值和最大值,所以您必须创建一个数组int[] numbers = new int[times],其中 - 次 - 是数组的大小。您还必须为现在的 MIN、MAX 和 TOTAL 创建一些变量(假设总数是所有数字的总和)。然后你必须现在哪个是最小值或最大值(查看 IF STATEMENTS )。
    • 所以到现在你只需要创建一个变量int total = 0; 把它放在int max = Integer.MIN_VALUE; 之后然后在循环的每个循环中(for)将数字添加到total: total += number 这一行将在numbers[i] = number; 之后。如果您需要其他东西,请现在让我!希望我的简短解释有帮助
    • 这条线有什么用处?数字[i] =数字;
    • 就是把用户给的数字存入Array。数组的名称是“数字”,用户键入的数字名称是数字。因此,每次用户输入一个数字时,它都会存储在数组中 i 位置的数字中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 2012-06-21
    • 2012-05-05
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多