-1

How can I input many lines in Java without knowing what is the limit of input? This is for competitive programming.

For example this input

4568
3258
124569
14789

I have to read all in one click, but how is that possible if I don't know the limit of input lines that I receive? Maybe next time I'll receive 34.

I was looking for something and I have this, but it didn't work:

Scanner sc = new Scanner(System.in); 
String text;

while(sc.hasNextLine()){
    text = sc.nextLine();
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • `text.nextLine();` should be `text = sc.nextLine();`. Then you need to do something with the line you just read ... – Stephen C Aug 29 '23 at 01:12
  • 3
    Please translate the title, too – ChrisGPT was on strike Aug 29 '23 at 01:20
  • Duplicate of [*How do I split a string in Java?*](https://stackoverflow.com/q/3481828/642706) – Basil Bourque Aug 29 '23 at 04:04
  • 1
    Duplicate of [*How can I repeatedly read user input using Scanner java*](https://stackoverflow.com/q/19537515/642706) – Basil Bourque Aug 29 '23 at 04:05
  • If the standard input is not closed you cannot detect that there will be no more lines, you will need to use two threads: one for reading the standard in and pushing lines to the other thread using a queue or something, and one thread for processing those inputs. – Mark Rotteveel Aug 30 '23 at 09:38
  • *"I have to read all in one click, but how is that possible if I don't know the limit of input lines that I receive? Maybe next time I'll receive 34."* When I read that, I was thinking you were using a GUI that used a text component. But, your code shows you are trying to use stdin. If you mean you need to save each line, I suggest storing them in an [`ArrayList`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html). A `List` is one of several containers in Java `Collection`s framework that has the ability to grow. – Old Dog Programmer Sep 01 '23 at 14:03

0 Answers0