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.
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
+ 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
+ 1
Rizal So like
String[] textArray = (sc.next());
? Iāll try it on my PC in the morning
+ 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.
+ 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
0
Paul, I donāt see anywhere in there about making arrays out of a text file?
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!