简体   繁体   English

可以通过扫描仪输入循环吗?

[英]Possible to loop through scanner input?

I've just started learning java and I can't seem to find a way to use for loop for a simple user input. 我刚刚开始学习Java,但似乎找不到一种用于简单用户输入的for循环方法。 Let's say that I have to enter an unknown number of hw scores, but I don't know it until the user actually enters it in. The problem is that I have to be add the scores the user entered. 假设我必须输入未知数量的硬件分数,但是直到用户实际输入时我才知道。问题是我必须添加用户输入的分数。 How do I go about looping the Scanner portion of the problem. 我该如何循环出现问题的“扫描仪”部分。

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?

You can use scanner without loop in here.(with a loop is also possible ). 您可以在此处使用不带循环的scanner 。(也可以带循环)。 you can try in this way. 您可以通过这种方式尝试。

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

Inputs: 输入:

45 58 5 5 66 1

Out put: 输出:

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

Next part of your question is about finding the average. 问题的下一部分是关于求平均值的。

You can find the sum by adding all elements of List , and divide sum by number of elements in the List 您可以通过添加List所有元素来找到总和,然后将总和除以List的元素数量

You can use a for loop fot the input. 您可以在输入中使用for循环。 It would good sense to define the scanner in the for loop because you only need the scanner in the loop, but java syntax makes the result ugly, so define it before the loop: 最好在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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM