【问题标题】:Possible to loop through scanner input?可以循环扫描仪输入吗?
【发布时间】:2014-10-06 05:59:05
【问题描述】:

我刚刚开始学习 java,但我似乎无法找到一种方法来使用 for 循环进行简单的用户输入。假设我必须输入未知数量的硬件分数,但直到用户实际输入时我才知道。问题是我必须添加用户输入的分数。我该如何去循环问题的扫描器部分。

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?

【问题讨论】:

    标签: java


    【解决方案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
    

    输出:

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

    您问题的下一部分是关于求平均值。

    你可以通过将List的所有元素相加得到总和,然后将总和除以List中的元素个数

    【讨论】:

      【解决方案2】:

      您可以在输入中使用 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;
      

      【讨论】:

      • scanner.next() 帮了大忙。
      猜你喜欢
      • 2015-12-23
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 2016-02-06
      • 2012-09-27
      • 2016-01-26
      相关资源
      最近更新 更多