Java: adding to a string array in a while loop using a file reader -
i have been making little program needs read list of golf courses changeing , needs called when ever. here code:
public class courses { public string[] courselist; public void loadcourses() throws ioexception{ int count = 0; int counter = 0; file f = new file("src//courses//courses.txt"); bufferedreader reader = new bufferedreader(new filereader(f)); while(count<1){ string s = reader.readline(); if(s.equalsignorecase("*stop*")){ reader.close(); count = 5; }else{ courselist[counter] = s; counter++; } s = ""; } } }
and in txt file.
riverchase steward peninsula lake park coyote ridge *stop* now when ever start run program because call method instantly gives me throw exeption , because of array. , need stay , array because use in jcombobox. if can or fix problem. im doing wrong, im noob. help. in advance. know file reader , stuff works because prints out system correct, need writing array repetedly.
change code assign new array during loadcourses(), , add call loadcourses() constructor:
public class courses { public string[] courselist; public courses() throws ioexception { // <-- added constructor loadcourses(); // <-- added call loadcourses } public void loadcourses() throws ioexception { int count = 0; int counter = 0; file f = new file("src//courses//courses.txt"); bufferedreader reader = new bufferedreader(new filereader(f)); list<string> courses = new arraylist<string>(); // <-- list can grow while(true){ string s = reader.readline(); if (s.equalsignorecase("*stop*")){ break; } courses.add(s); } courselist = courses.toarray(new string[0]); // <-- assign here } } this ensures when create instance, starts out life array initialised. not not error, data correct (unlike other answers create empty (ie useless) array.
note code work number of course names in file (not 5).
Comments
Post a Comment