gpt4 book ai didi

java - 显示最小值、最大值、平均值和输入的数字

转载 作者:行者123 更新时间:2023-12-01 16:51:17 26 4
gpt4 key购买 nike

这是我到目前为止所得到的,但不知道如何显示数量用户输入的数字,我知道它与 count 方法有关,但不知道如何将其实现到此。

import java.util.Scanner;

public class Test {

@SuppressWarnings("resource")
public static void main(String[] arg) {
int count = 0;
double sum = 0;
double maximum = 0;
double minimum = 100;

Scanner kb = new Scanner(System.in);

double input = -1;
// Main processing loop...
do {

// Validation loop...
do {
System.out.println("Please enter a number or 0 to quit:");
input = kb.nextDouble();
kb.nextLine();
} while (input > 100);

if (input > 0) {
count++;
sum += input;

if (maximum < input) {
maximum = input;
}

if (minimum > input) {
minimum = input;
}
}
} while (input != 0);

double average = (sum / count);

System.out.println(
"The average is: " + average);
System.out.println(
"Minimum of entered numbers: " + minimum);
System.out.println(
"Maximum of entered numbers: " + maximum);

}

}

最佳答案

将输入的项目添加到列表中。

您创建一个列表:

List<Integer> list = new ArrayList<>();

然后您可以使用以下命令将项目添加到列表中:

list.add(input);

最后,您获得了所有输入的集合,并且可以更好地使用。

优点是您可以返回所有输入并再次使用它们。

要获取大小,您可以使用以下两者:

System.out.println(count);       -- using your variable
System.out.println(list.size()); -- get from the list

关于java - 显示最小值、最大值、平均值和输入的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39678619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com