简体   繁体   English

根据用户输入构造双精度值数组

[英]Constructing array of double values from user input

So i wanted to produce a program in which the user is prompted to input as many Double values as they want, and the program stores these values in an array until the EOF (when the user presses ctl + d), and then prints the sum of these numbers to output. 因此,我想制作一个程序,在该程序中,提示用户输入所需的Double值,该程序将这些值存储在数组中,直到EOF(当用户按ctl + d时),然后打印总和这些数字中的一个输出。 This is what i have so far: 这是我到目前为止所拥有的:

import java.io.*;
import java.util.*;

public class ArrayExample {

 public static void main(String[] args) {

  Scanner keyboard = new Scanner(System.in);
  System.out.print("Enter line: ");
  ArrayList<Double> nums = new ArrayList<Double>();
  double input = keyboard.nextDouble();

  while (input.hasNextLine()) {
   input = keyboard.nextDouble();
  }
  System.out.print(nums);
  double sum = 0;
  for (int i = 0; i < nums.size(); i++) {
   sum+=Integer.parseInt(nums.get(i));
  System.out.println(sum);
  }
 }
}

My questions were how would i use a loop to keep reading input doubles until EOF, is the ArrayList the best way to store the users inputs and is that the most correct way to get the sum? 我的问题是我将如何使用循环来使输入翻倍直到EOF,ArrayList是存储用户输入的最佳方法,并且是获取总和的最正确方法吗? Thank you! 谢谢!

Modify the while and for loops as per the snippet below. 按照下面的代码片段修改whilefor循环。 In the while loop, just use Scanner's hasNextDouble() method directly and add values to your Arraylist as they are entered. 在while循环中,只需直接使用Scanner的hasNextDouble()方法并将输入的值添加到Arraylist中即可。 In the for loop, you don't need to parse the values to integers since sum is a double which is the datatype of your Arraylist. for循环中,您无需将值解析为整数,因为sum是一个double值,这是Arraylist的数据类型。 Arraylist is right for your case since you are not sure of how many values you will get from the user; Arraylist适合您的情况,因为您不确定将从用户那里获得多少值; Arraylists are resizable. 数组列表可调整大小。

  while (keyboard.hasNextDouble()) {
      nums.add(keyboard.nextDouble());
  }
  keyboard.close();
  System.out.println(nums);
  double sum = 0;
  for (int i = 0; i < nums.size(); i++) {
   sum += nums.get(i);
  }
  System.out.println(sum);

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

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