Reading strings from file to array of strings
Trying to read a set of strings and store each line of the text file into a string array entry
//FILE:
abcd
efgh
jklm
//TO...
String [] myString = {"abcd","efgh","jklm"};
The problem is that every time read from file and print the array..it only stores the first line of the text file in the array.
try{
FileReader theReader =new FileReader("Amaze.txt");
BufferedReader in =new BufferedReader(theReader);
String theLine;
theLine = in.readLine();
while ( theLine !=null ){
mazeString = theLine.split("\n");
theLine = in.readLine();
}
in.close();
}
catch (IOException e){// System.out.println("oops:\n" + e); }
}
[1184 byte] By [
JoeDonea] at [2007-11-27 5:09:23]

You're acting as if the line you read is the whole file. The line you read won't have any \n's in it by definition, since it is a line! The file, however, will look like TEXT\nTEXT\nTEXT\n etc.
So there's no need to split it... every time you read a line just add it to your array or collection.
You have to index an array when you initialize and/or refer to any given part of it.
String[] myArray = new String[10];
int i = 0;
while ( (in.readLine())!= null && i < myArray.length) {
myArray[i++] = in.readLine();
}
> Why not use a list instead of an array? Who uses
> arrays anyway ;-)
True, true...
List<String> myList = new List<String>;
while ( (in.readLine())!= null) {
myList.add( in.readLine() );
}
I'm sure you meant:
String line
List<String> myList = new ArrayList<String>();
while ( (line = in.readLine())!= null) {
myList.add(line);
}
The repeated call to readLine is especially heinous.
> I'm sure you meant:
[snip]
> The repeated call to readLine is especially heinous.
doh...
I'm writing a psychic/telepathic compiler -- that was one of my test cases from earlier ;). I expect release sometime in 2015.
Besides, if you don't leave a bug in there every now and then, how are the newbies ever gonna learn to debug >:)?