I'm trying to write a program that will take numbers input through a user and store the numbers into an ArrayList. Currently I have:
public static void main(String[] args) {
System.out.println(numberstorage());
}
public static ArrayList<Double> numberstorage() {
Scanner s = new Scanner(System.in);
ArrayList<Double> numbers = new ArrayList<Double>();
System.out.println("Enter a number between 0 - 100");
do {
numbers.add(s.nextDouble());
} while (s.nextDouble() != 0);
s.close();
return numbers;
}
When I input 1, 2, 3, for some reason my output is 1.0, 3.0. Is there a reason it's skipping one line of input?
You call s.nextDouble()
twice per loop -- once to add it to numbers
, and once to check the while
condition.
Instead, you only want to call it once, and use the same value each time. Store it in a variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.