gpt4 book ai didi

java - 如何一次只允许一个参数

转载 作者:行者123 更新时间:2023-12-01 13:29:42 24 4
gpt4 key购买 nike

我允许用户通过命令行输入数字。我想这样做,以便当用户一次在命令行上输入多个数字时,它会显示一条消息,要求输入一个数字,然后按 Enter 键。然后继续。

这是我的代码。如果有人能告诉我如何实现这一点,我将不胜感激。

import java.util.ArrayList;
import java.util.InputMismatchException;
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
try{
myArr.add(scan2.nextDouble());
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
catch (InputMismatchException e) {
System.out.println("Stop it swine! Numbers only! Now you have to start over...");
main(args);
return;
}

inputs = scan.nextLine();
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
}

最佳答案

正如问题评论中所建议的:不要扫描您阅读的数字行,而是使用 Double.valueOf 将其解析为单个数字。 (我还稍微美化了你的其余代码,请参阅其中的评论)

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:");

// we can use a for loop here to break on q and read the next line instead of that while you had here.
for (String inputs = scan.nextLine() ; !inputs.matches("[qQ]") ; inputs = scan.nextLine())
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
try{
myArr.add(Double.valueOf(inputs));
count++; //that'S even shorter than count += 1, and does the exact same thing.
System.out.println("Please enter another number or press Q for your average");
}
catch (NumberFormatException e) {
System.out.println("You entered more than one number, or not a valid number at all.");
continue; // Skipping the input and carrying on, instead of just starting over.
// If that's not what you want, just stay with what you had here
}

}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}

(代码未经测试,因此可能存在错误。如果您有错误,请通知我;))

关于java - 如何一次只允许一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21643592/

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