0

How do I go about taking input that is multiple lines, such as

4 2 9
1 4 2
9 8 5

and placing it into an array of that is big enough to hold each line with no empty positions, or an arraylist. I've tried many ways to do this and cannot find a solution. For example, if the user copied and pasted the above snippet as input, I want an array or arraylist to hold

["4 2 9", "1 4 2", "9 8 5"] 

3 Answers3

0

try this:

List<String> list = new ArrayList<String>();
 while((str = in.readLine()) != null){
 list.add(str);
}
Amol Raje
  • 928
  • 3
  • 9
  • 16
  • While loop never terminates and is constantly checking for new lines –  Dec 06 '17 at 17:06
0

You can use Scanner to read the input from console.

Try something like this:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    List<String> list = new ArrayList<String>();

    while(scan.hasNextLine()) {
        String str = scan.nextLine();
        System.out.println(str);
        list.add(str);
    }

    System.out.println(java.util.Arrays.toString(list.toArray()));

    scan.close();
}
Parth Soni
  • 11,158
  • 4
  • 32
  • 54
  • This way the while loop never terminates because scan.nextLine() is always looking for input –  Dec 06 '17 at 17:03
  • @HarunFeraidon: There's no other way to do it. If you know the number of rows that you'll read then you can manually loop for a specific number of time. – Parth Soni Dec 08 '17 at 05:02
0

Try calling nextLine

Scanner s = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
while (s.hasNextLine()) {
    list.add(s.nextLine());
}

System.out.println(list);

Note that the scanner will keep prompting for input. To stop this, you need to enter an end of line character. See this answer for how to do this.

Example input/output:

4 2 9
1 4 2
9 8 5
^D
[4 2 9, 1 4 2, 9 8 5]
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • That works but is there a way I can do it where the user doesn't have to manually terminate the program? I want the compiler itself to know when there is no more input. If there is no way then that's okay, thank you –  Dec 06 '17 at 17:03
  • There is no way to do that, I'm afraid. @HarunFeraidon – Sweeper Dec 06 '17 at 17:05