Masoum
Masoum

Reputation: 91

use scanner to store lines to an array

I need to copy the data which I have and then paste it to the java Eclipse Console output window, this data contains some lines and there is a word in each line. I don't know how many lines it has. How could I store the lines in an array? I tried this code but after pasting the data, I should press the keyboard Enter key two times. It also stores the even lines (Not all lines). How may I fix it? Thanks

import java.util.ArrayList;

import java.util.Scanner;

public class SCAN {

    public static void main(String[] args) {
        ArrayList<String> lines = new ArrayList<String>();
        Scanner s = new Scanner(System.in);
        while(s.hasNextLine()){
            String line = s.nextLine();
            if(line.length() > 0) {
                lines.add(s.nextLine());
            } else {
                break;
            }
        }
        System.out.println(lines);
}
}

Upvotes: 0

Views: 3335

Answers (2)

Swapnil Sharma
Swapnil Sharma

Reputation: 11

Try this.

Scanner read=new Scanner(System.in);

for(int i=0; i<size; i++) {
    array[i]=read.next();
    array[i]+=read.nextLine();
}

Upvotes: 0

Akash Thakare
Akash Thakare

Reputation: 22972

Change lines.add(s.nextLine()); to lines.add(line);

Whats Happening here is you are using nextLine() twice.

So first Line got read and stored to line but after that it reads second one which is stored to ArrayList so first line which you have stored won't be there in ArrayList.

I should press the keyboard Enter key two times.

Yes You have to because you are breaking loop when you don't have line.


If you want to enter Specific lines you can use counter for Number of lines.

You can prompt by Scanner to insert specific value for counter.

    int i=0;
    while(s.hasNextLine()){
        String line = s.nextLine();i++;
        if(line.length() > 0) {
            lines.add(line);
        } else {
            //don't add empty Line
        }
    if(i==2)break;
    }

Upvotes: 4

Related Questions