-2

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
  • 50,121
  • 5
  • 26
  • 72
  • 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

2 Answers2

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
  • 519
  • 3
  • 12
0

Do it as follows:

import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(new BufferedInputStream(System.in));
        ArrayList<String> inp = new ArrayList<>();
        String line;
        System.out.println("Enter a multiline text (press Enter without any text to exit): ");
        while ((line = in.nextLine()) != null && line.length() != 0) {
            inp.add(line);
        }
        System.out.println("The list:");
        System.out.println(inp);
        System.out.println("-------------------------------------------------------------");

        // Output using index
        System.out.println("Item at index 0: " + inp.get(0));
        System.out.println("Item at index 1: " + inp.get(1));
    }
}

A sample run:

Enter a multiline text (press Enter without any text to exit): 
HELLO I ATE APPLE
APPLE IS GOOD 
I ATE MORE

The list:
[HELLO I ATE APPLE, APPLE IS GOOD , I ATE MORE]
-------------------------------------------------------------
Item at index 0: HELLO I ATE APPLE
Item at index 1: APPLE IS GOOD 

Notes:

  1. Use nextLine instead of next to read a line from the input text.
  2. Study the documentation on BufferedInputStream and Scanner.
Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72