可以循环扫描输入?

时间:2014-10-06 05:59:06

标签: java

我刚刚开始学习java,我似乎无法找到一种方法来为简单的用户输入使用for循环。假设我必须输入未知数量的hw分数,但在用户实际输入之前我不知道。问题是我必须添加用户输入的分数。如何循环解决问题的扫描程序部分。

import java.util.Scanner;

public class HomeworkCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Please enter the homework scores:");
double hwScores = scanner.nextDouble();

//how can I loop through the number of homework added on plus 
//add the sum and find the average?

2 个答案:

答案 0 :(得分:1)

你可以在这里使用scanner无循环。(也可以使用循环)。你可以这样试试。

Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the homework scores in" 
                                          +"a single line by separate by space");
List<Double> list = new ArrayList<>();
String str = scanner.nextLine();
for(String i:str.split(" ")){
   list.add(Double.parseDouble(i));
}
System.out.println(list);

输入:

45 58 5 5 66 1

Out put:

[45.0, 58.0, 5.0, 5.0, 66.0, 1.0]

问题的下一部分是关于找到平均值。

您可以通过添加List的所有元素来查找总和,并将总和除以List

中的元素数量

答案 1 :(得分:0)

您可以在输入中使用for循环。在for循环中定义扫描器是很有意义的,因为你只需要循环中的扫描器,但java语法会使结果变得难看,所以在循环之前定义它:

double total = 0.0;
int count = 0;
System.out.println("Please enter the homework scores (negative to end):");
Scanner scanner = new Scanner(System.in); 
for (double score = scanner.nextDouble(); score > 0; score = scanner.nextDouble()) {
    total += score;
    count ++;
    scanner.next(); // you need this to clear the newline from the buffer
}
double average = total / count;
相关问题