1

Code:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<Integer> array = new ArrayList<>();
        while(scanner.hasNextInt()){
            array.add(scanner.nextInt());
        }
        System.out.println(array);
    }
}

Input: enter image description here

Why while doesnt brake the loop when i enter empty line?

  • Do you ever close the input stream? If not, how does the scanner know there won't be another value in the future? [Your code runs fine](https://ideone.com/4kd5I1) if the input is piped in, rather than coming from a terminal. – Andy Turner May 12 '20 at 17:49
  • Try using a sentinel value that will terminate the loop.For instance if user enters -1 exit the loop and print the contents of the array – snm May 12 '20 at 17:58

0 Answers0