如何显示我在Java中输入的数字

时间:2018-03-26 02:02:21

标签: java

我正在写一个程序,最后我必须显示我输入的数字以及输入数字的最大值和最小值。但是我遇到了一个小问题,这是我的代码,

import java.util.*;

public class question3controlstructures {
    public static void main (String [] args) {
        Scanner in = new Scanner (System.in);

        int numberEntered;
        int numbersinput = 0;
        String answer ="";
        double sum = 0;
        do {
            System.out.println("Enter a number");
            numberEntered = in.nextInt();
            numbersinput ++;
            System.out.println("do you want to enter another number?");
            answer = in.next();
            sum = sum + numberEntered;
        } while (answer.equals("yes"));

        System.out.println("The sum is: " + sum);
        System.out.println("The average is: " + sum/numbersinput);
        System.out.println(numberEntered);
    }
}

3 个答案:

答案 0 :(得分:0)

以上评论绝对有用。但是,这里的代码很少

@PostMapping(path = "/uploadLogo")
public void uploadLogo(@RequestParam("image") MultipartFile file) {
    System.out.println("");
}

在评论中,您需要一个列表来存储输入的多个编号。

答案 1 :(得分:0)

每次输入数字时,只需比较最小值和最大值

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

    int numberEntered;
    int numbersinput = 0;
    String answer ="";
    double sum = 0;
    do {
        System.out.println("Enter a number");
        numberEntered = in.nextInt();

        System.out.println("YOU HAVE ENTERED: " + numbersEntered);
        if (min > numberEntered) min = numberEntered;
        if (max < numberEntered) max = numberEntered;

        numbersinput ++;
        sum = sum + numberEntered;

        System.out.println("do you want to enter another number?");
        answer = in.next();
    } while (answer.equals("yes"));

    System.out.println("The sum is: " + sum);
    System.out.println("The average is: " + sum/numbersinput);
    System.out.println(numberEntered);

    //you can print your min max here.

答案 2 :(得分:0)

IntSummaryStatistics类和Java 8的Stream API可能不如手动处理min,max,sum和avg计算那么冗长。

public static void main(String[] args) {
    // Get user input.
    List<Integer> numbers = new ArrayList<>();
    Scanner scanner = new Scanner(System.in);
    while (scanner.hasNextInt()) {
        // No user friendly way to gather user input, improve!
        numbers.add(scanner.nextInt());
    }

    // Transform input to statistics.
    IntSummaryStatistics stats = numbers.stream()
        .collect(Collectors.summarizingInt(Integer.intValue()));

    // Print statistics.
    String jointNumbers = numbers.stream()
        .collect(Collectors.joining(", "));
    System.out.printf("You entered %d numbers: %s\n, stats.getCount(), jointNumbers);
    System.out.println("Min: " + stats.getMin());
    System.out.println("Max: " + stats.getMax());
    System.out.println("Sum: " + stats.getMax());
    System.out.println("Avg: " + stats.getAverage());
}