[英]how do i create a limit of command line entries in java
我的程序允許您輸入數字,然后按Enter。 然后程序要求您再給它一個數字,直到得到21個數字。 關鍵是它可以為您提供平均值。 如果需要,您可以在一個條目上輸入盡可能多的數字,它仍然可以使用。 我該怎么做,這樣您一次只能輸入一個數字?
另外,如何停止除數字外的所有條目?
import java.util.ArrayList;
import java.util.Scanner;
class programTwo
{
private static Double calculate_average( ArrayList<Double> myArr )
{
Double sum = 0.0;
for (Double number: myArr)
{
sum += number;
}
return sum/myArr.size(); // added return statement
}
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
String inputs = scan.nextLine();
while (!inputs.matches("[qQ]") )
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
myArr.add(scan2.nextDouble());
count += 1;
System.out.println("Please enter another number or press Q for your average");
inputs = scan.nextLine();
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}}
如果用戶鍵入的不是“ q”或“ Q”之外的其他InputMismatchException
也不是有效數字),則將引發InputMismatchException
。 您只需要捕獲該異常,顯示一條適當的消息,然后要求用戶繼續即可。 可以按照以下步驟進行:
try {
myArr.add(scan2.nextDouble());
count += 1;
} catch (InputMismatchException e) {
System.out.println("Very funny! Now follow the instructions, will you?");
}
您的其余代碼無需更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.