1

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?

1 Answer 1

2

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
}
1
  • Thank you! It helped, now i can finally finish the program.
    – daniel p
    Feb 10, 2015 at 1:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.