查找用户输入的数字列表中的最小和最大数字

时间:2018-04-26 23:34:18

标签: java

我需要帮助显示用户输入的平均值,最小值和最高值,但我只能显示平均值和最大值。这里还有另外一个问题,但它并没有完全解决,只给出了最小的数字。如果有除Math.min和Math.max以外的其他方式,那将非常感激。

import java.text.DecimalFormat;
import java.util.Scanner;

public class ProblemSet3_1 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    DecimalFormat dec = new DecimalFormat();

    int snum = 0;
    int height = 0;
    int add = 0;
    double avg = 0;
    int largest = 0;
    int smallest = 0; 


    System.out.print("How much students are in your class?" + '\n');
    snum = input.nextInt(); 


    for (int i = 1; i <= snum; i++) {
        System.out.print("How tall is student #" + i + "?" + '\n');
        height = input.nextInt();

        add += height;
        avg = add / i;

        if (height > largest) {
            largest = height;
        }

    }
    System.out.print("The average height is " + avg + ", while the tallest is " + largest + " , and the shortest is " + smallest +  ".");

    }
}

3 个答案:

答案 0 :(得分:3)

是的,这是一个使用流的非常简单的方法:

IntSummaryStatistics stats = IntStream.generate(input::nextInt).limit(snum)
    .summaryStatistics();

stats对象现在包含平均值,计数,最大值,最小值,总和。

编辑:对不起刚刚意识到您还想要一条提示信息:

IntStream.rangeClosed(1, snum).map(i -> {
    System.out.println("How tall is student " + i + "?");
    return input.nextInt();}).summaryStatistics();

答案 1 :(得分:1)

在for循环中,执行:

if(i==1){
smallest= height;
largest=height;
}
else {
 if(height< smallest)
   smallest = height
 if(height>largest)
     largest = height
}

答案 2 :(得分:0)

可以添加一个简单的if / else if语句

import java.text.DecimalFormat;
import java.util.Scanner;

public class ProblemSet3_1 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        DecimalFormat dec = new DecimalFormat();

        int snum = 0;
        int height = 0;
        int add = 0;
        double avg = 0;
        int largest = 0;
        int smallest = 0; 


        System.out.print("How much students are in your class?" + '\n');
        snum = input.nextInt(); 


        for (int i = 1; i <= snum; i++) {
            System.out.print("How tall is student #" + i + "?" + '\n');
            height = input.nextInt();

            add += height;
            avg = add / i;
            if(i == 1) {
                smallest = height;
            }
            else if(height < smallest){
                smallest = height;
            }
            if (height > largest) {
                largest = height;
            }

        }
        System.out.print("The average height is " + avg + ", while the tallest is " + largest + " , and the shortest is " + smallest +  ".");

    }
}