0

I have a text file that looks something like this:

1 Song one
2 Song two
3 Song three
...

How do I read a line by line and extract number and String separately from a single line, and let's say print them to the console with:

String title; // extracted from current line
int num; // extracted from current line    
System.out.println("Number: " + num + "Title: " + title);
  • https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Scanner.html – markspace Mar 29 '20 at 21:20
  • Have you tried something? If so, share with us the code so that we can better guide you on the problems you are facing. – Eduardo Mar 29 '20 at 21:21
  • Does this answer your question? [How to read a large text file line by line using Java?](https://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java) – Cray Mar 30 '20 at 07:28

1 Answers1

0

How do I read a line by line

Use a BufferedReader and its readLine() method.

How do I extract number and String separately

Use line.indexOf(' ') then substring(...) to get the 2 parts.

Then use Integer.parseInt(...) on the first part to get number.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • How do I implement indexOf() if i have let's say more than 100 songs and the song title begins after the number separated only by a space? –  Mar 29 '20 at 21:41
  • You're using `indexOf` on a string containing only one line from the file, i.e. only one song, not 100 songs. – Andreas Mar 29 '20 at 21:51
  • I know but what i meant is, it's not the same index when i have a one digit number and when you have 3 or 4 digit number... –  Mar 29 '20 at 23:42
  • Which is why you're calling `indexOf` first, to find the index of the space. Otherwise, why did you think I told you to call `indexOf`? What purpose would it have, if not that? I mean, you do know what it does, right? If not, which part of the documentation I linked to did you not understand? – Andreas Mar 29 '20 at 23:49