![](/img/trans.png)
[英](Java) How to Keep Track of Numbers Entered by User for Determining Min and Max
[英]Displaying min, max, average, and numbers entered
這是我到目前為止的結果,但無法弄清楚如何顯示用戶輸入的數字,我知道它與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
如果您嘗試使用輸入,則需要將其保存在某處。 數組將是您的最佳選擇(array,ArrayList等)。
編輯:如果要添加負數, if (input > 0)
更改為if (input != 0)
(我猜您是從此處將輸入添加到數組中的)。
只需更改if條件邏輯使用if (input != 0 ) {
代替if(input > 0 )
嘗試如下。
if (input != 0 ) {
....
}
System.out.println("User enters total Numbers: "+count);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.