gpt4 book ai didi

java - 如何在一行上有多个输入,所有输入都传递到带有可变参数的方法中

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

好吧,所以我得到了这个作业,它要求我有一个具有可变数量输入和字符串输入的方法。所有输入都必须在扫描仪中的一行上,并且该方法必须返回输入的值的数量、平均值、最大值、最小值和输入的字符串。

这是终端窗口的示例。

Please enter the name of the course: CourseNameHere
Please enter the scores for CSC 201 on a single line and type a -1 at the end
71 02 81 44 84 17 38 11 20 05 93 -1

The course name : CourseNameHere
Number of Scores : 11
The Average Score : 42.37
The Minimum Score : 02
The Maximum Score : 93

平均分数必须四舍五入到小数点后两位(我认为我可以处理)对我来说唯一的问题是在单行上扫描可变数量的输入,以及如果我没有在输入之间按 Enter 键,如何让程序计算输入的数量。这是我到目前为止所拥有的。但我不知道从这里去哪里。我可以让它询问顺序值,但它们并不都在同一行

public static int calculate(int again)
{
Scanner input = new Scanner(System.in);
int numberOfValues = 0;
int max = -9999;
int min = 100000;
int sum = 0;
double value;

System.out.print("What is the name of the course you wish to evaluate? : ");
String courseName = input.next();
System.out.println("Please enter the scores for the class, press enter between each value." + "\n" + "Enter -1 to finish and calculate.");
for(value = 0; value != 1; numberOfValues++)
{
value = input.nextDouble();
sum += value;





}

最佳答案

答案取决于方法的输入。您收到的是 Stringint 数组还是 StringString。也就是说,用户的输入是否已经为您分解了?

例如...

Scanner kb = new Scanner(System.in);
String courseName = kb.nextLine();
String scoreLine = kb.nextLine();

// courseName and scoreLine now become the parameters to you method...

// You could then use another scanner to break the line down...
Scanner scoreLineScanner = new Scanner(scoreLine);

while (scoreLineScanner.hasNextInt()) {
int score = scoreLineScanner.nextInt();
if (score != -1) {
// Calculate other values...
} else {
break;
}
}

我确实考虑过使用 String#split(""),但是您可能需要自己将每个元素转换为 int,这可能会也可能不会合适(有点乱)

关于java - 如何在一行上有多个输入,所有输入都传递到带有可变参数的方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19171579/

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