How would you read from a text file and turn it into an array? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How would you read from a text file and turn it into an array?

For a practice project I’m working on, I need a long list of names that will be randomly pulled from. Instead of making an array in my class that’s incredibly long, I want to put all the names in a .txt file and pull them from there. The Files lesson on here does not cover that well.

12th Aug 2019, 6:19 AM
p.xela
p.xela - avatar
7 Answers
+ 1
Once you've read how to read files, have a look at this: https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java#3481842
12th Aug 2019, 6:24 AM
Paul Grasser
Paul Grasser - avatar
+ 3
I think you can make an array using the example code in the second File lesson by change the body of while block, assigning each names in array instead of print the names
12th Aug 2019, 7:14 AM
Rizal
Rizal - avatar
+ 1
Rizal So like String[] textArray = (sc.next()); ? I’ll try it on my PC in the morning
12th Aug 2019, 7:50 AM
p.xela
p.xela - avatar
+ 1
p.xela read the file in a string, and split it up at a specific separator. Let's say the names are stored like this in the string after reading the file: "John,Josh" Then you can split it at the "," using the link I provided.
12th Aug 2019, 8:14 AM
Paul Grasser
Paul Grasser - avatar
+ 1
p.xela You should declaring the array outside the while block first String[] textArray=new String [...]; ... while (sc.hasNext ()){ int i=0; textArray [i]=sc.next(); i++; } Hope this help, actually I have never tried make an array from .txt file :/ You can try the solution given by Paul Grasser
12th Aug 2019, 8:21 AM
Rizal
Rizal - avatar
0
Paul, I don’t see anywhere in there about making arrays out of a text file?
12th Aug 2019, 6:40 AM
p.xela
p.xela - avatar
0
Paul Grasser 💻 Hey just wanted to give you an update that I got it work with your suggestion! Took me a while, but I got it with the split thing. Thanks!
19th Aug 2019, 6:00 AM
p.xela
p.xela - avatar