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. 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? Thank you!
nums.add(keyboard.nextDouble());but get rid of the whole line...input = keyboard.nextDouble();and also you might just want to dokeyboard.hasNextDouble();as your while loop condition... as of right now though your code does not compile because you do..while(input.hasNextLine())Also... no need for thesum += Integer.parseInt(nums.get(i));just simply do...sum += nums.get(i);hasNextLine(), it just won't work at runtime.input.hasNextLine()that doesn't make any sense... consideringinputis a doublehasNextLine()tohasNextDouble(), and didn't notice that you also correctedinputtokeyboard.sum, and you can calculate that as the user enters values. And,Integer.parseInt(nums.get(i))is not what I would call a best practice.