1

I have been making a little program that needs to read a list of golf courses that could be changeing and needs to be called when ever. Here is the 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 now this is what is in the txt file.

    RiverChase 
    Steward Peninsula 
    Lake Park 
    Coyote Ridge 
    *stop* 

Now when ever i start to run the program because i call the method instantly it gives me a throw exeption and it is because of the array. And i need to stay and array because i use it in a JComboBox. If you can help or fix the problem. Most likely im just doing it wrong, im a noob. Just help. Thanks in advance. I know all the file reader and stuff works because it prints out to the system correct, i just need help writing it to the array repetedly.

tyty5949
  • 1,480
  • 5
  • 14
  • 17
  • Your basic problem is that arrays in Java are not dynamic sized. Lots of good info on this in the following question: [java dynamic array sizes?](http://stackoverflow.com/questions/1647260/java-dynamic-array-sizes) – David Gelhar Jun 06 '12 at 02:56
  • 1
    You must check the result of readLine() for null before you do anything else with it. If null, it is EOF: close the file. – user207421 Jun 06 '12 at 02:58

4 Answers4

2

You should initialize your array before using it

public static final MAX_SIZE = 100;
public String[] courselist = new String[MAX_SIZE];
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
1

You'd better create a List that is easier to manipulate and convert it as an array at the end of the process :

    List<String> list = new ArrayList<String>();
    String [] array = list.toArray(new String [] {});

Here is a possible implementation of the loading using a List :

public static String [] loadCourses() throws IOException {
    File f = new File("src//courses.txt");
    BufferedReader reader = new BufferedReader(new FileReader(f));
    List<String> courses = new ArrayList<String>();
    while (true){
        String s = reader.readLine();
        if (s == null || s.trim().equalsIgnoreCase("*stop*")){
            break;
        } else{
            courses.add(s);
        }
    }
    return courses.toArray(new String [] {});
}

Also why use a stop keyword ? You could simply stop the process when you reach the end of the file (when s is null).

Arnaud
  • 7,259
  • 10
  • 50
  • 71
  • Thanks that helped but now i cant fiqure out how to apply that to the JComboBox. Please Reply – tyty5949 Jun 06 '12 at 03:41
  • Call this code where you create your combo box. Example : `String [] values = loadCourses(); JComboBox combo = new JComboBox(values);` – Arnaud Jun 06 '12 at 03:42
  • OHHHHHH i should have known that,thanks a ton.I will use this knowledge through out the rest of this project – tyty5949 Jun 06 '12 at 03:45
  • ok this is emmbarasing but it is not fixed i tried to do that like this public String[] = loadCourses(); in the courses class and it gives me an error. I then try to load it in the class with the jcombobox and it dosnt load anything. What did i do this time – tyty5949 Jun 06 '12 at 04:14
  • Cannot tell you unless i see more of your code. Did you change the method signature to `public static String []` ? – Arnaud Jun 06 '12 at 04:23
  • And static ? Also, in the code example you paste, i don't see variable name. It should be : `String [] courses = loadCourses();` – Arnaud Jun 06 '12 at 04:31
1

Change your code to assign a new array during loadCourses(), and add a call to loadCourses() to your constructor:

public class Courses {
    public String[] courselist;

    public Courses() throws IOException {  // <-- Added constructor
        loadCourses();                     // <-- Added call to 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>(); // <-- A List can grow 
        while(true){
            String s = reader.readLine();
            if (s.equalsIgnoreCase("*stop*")){
                break;
            }
            courses.add(s);
        }
        courseList = courses.toArray(new String[0]); // <-- assign it here
    }
}

This ensures that when you create an instance, it starts out life with the array initialised. Not only will you not get an error, but the data will always be correct (unlike other answers that simply create an empty (ie useless) array.

Note that this code will work with any number of course names in the file (not just 5).

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

Here some example, without using the *stop*:

public class ReadFile {

    public static void main(String[] args) {
        BufferedReader reader = null;
        List<String> coursesList = new ArrayList<>();
        String[] courses;

        try {
            File file = new File("courses.txt");
            reader = new BufferedReader(new FileReader(file));
            String readLine;

            do {
                readLine = reader.readLine();
                if(readLine == null)
                    break;

                coursesList.add(readLine);
            } while (true);
        } catch (IOException ex) {
            Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        courses = coursesList.toArray(new String[coursesList.size()]);

        for(int i = 0; i < courses.length; i++) {
            System.out.println(courses[i]);
        }
    }
}
Crazenezz
  • 3,416
  • 6
  • 31
  • 59