daniel p
daniel p

Reputation: 35

How can i use multiple scanners

I am having trouble figuring out how I can allow input that will consist of as many lines as the user wants. Input will consists of at least 1 line. On the first line will be an integer, this integer is suppose to tell the program how many lines are going to follow after, for ex.

    5
    line1
    line2 
    line3
    line4
    line5

What should I do? Is there a type of scanner that will allow this or should i use loops?

Upvotes: 1

Views: 585

Answers (1)

Alexis C.
Alexis C.

Reputation: 93842

You don't need multiple Scanner instances to handle this. Just use one instance with a loop is sufficient.

Scanner sc = new Scanner(System.in);
int nbLines = sc.nextInt();
sc.nextLine(); //consume the line separator token 
for(int i = 0; i < nbLines; i++) {
    String line = sc.nextLine();
    //do something with the line
}

Upvotes: 2

Related Questions