-3

Hello fellow programmers!

I am trying to write a java program where it reads multiple lines of input.

e.g.

HELLO I ATE APPLE
APPLE IS GOOD 
I ATE MORE

** There can be more lines of course.

I am trying to store every line in an ArrayList<String> i.e. I want to be able to store the above like this

list.get(0) = "HELLO I ATE APPLE"
list.get(1) = "APPLE IS GOOD"

etc...

Scanner in = new Scanner(System.in);
ArrayList<String> inp = new ArrayList<>();
while(in.hasNextLine()) {   
    Scanner liner = new Scanner(in.nextLine()); 
    while(liner.hasNext()) {        
        inp.add(liner.next());  
    }       
    liner.close();
}

BUT MY PROGRAM ABOVE STORES EVERY WORD AS A STRING...

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Don't use a second scanner. Just use `in`. Use `in.nextLine()` to read an entire line. – markspace Feb 11 '20 at 22:30
  • Does this answer your question? [How can I read input from the console using the Scanner class in Java?](https://stackoverflow.com/questions/11871520/how-can-i-read-input-from-the-console-using-the-scanner-class-in-java) – NotZack Feb 11 '20 at 22:32

1 Answers1

0

You don't need to make another scanner:

Scanner in = new Scanner(System.in);
ArrayList<String> inp = new ArrayList<>();
while(in.hasNextLine()) {
    inp.add(in.nextLine());
}
in.close();
The Zach Man
  • 738
  • 5
  • 15