Question

I need help reading from a file: my file looks exactly like that:

2,
Bob,
1,
Hand, 10.0, Broken,
John,
Leg, 20.0, Broken,
Hand, 10.0, Broken, //this comma has to be here

I need to load this data into array where Bob and John is stored, and injuries into arrayLists.

Default patient constructor creates arrayList for each of them.

My code looks like that:

public void load(File f) {
    try {
        BufferedReader br = new BufferedReader(new File Reader(f));
        String nextLine = br.readLine();
        while (nextLine!=null) {
        StringTokenizer st = new StringTokenizer(nextLine, ",");
        int numberOfPatients = Integer.praseInt(st.nextToken());

        for (int j=0 j<numberOfPatients; j++) {
            String name = st.nextToken();   // This is the place where I get NoSuchElementException
            int age = Integer.parseInt(st.nextToken());
            this.patients[j-1] = new Patient(name,age);
            int numberOfInjuries = Integer.parseInt(st.nextToken());

            for (int i=0; i<numberOfInjuries-1; i++) {
                String type = (st.nextToken());

                if (type.equals("Leg")) {
                    int cost = Integer.parseInt(st.nextToken());
                    String injury = st.nextToken();
                    // addInjury - function to add new injury to the arrayList
                    this.patients[j].addInjury(new Leg(cost, injury));
                } else if (type.equals("Hand")) {
                    int cost = Integer.parseInt(st.nextToken());
                    String injury = st.nextToken();
                    this.patients[j].addInjury(new Hand(cost, injury);
                }
            nextLine = br.readLine();
        }
        br.close();
    } catch(Exception ex) {
        System.out.println(ex);
        System.exit(1);
    }
}

It returns java.util.NoSuchElementException. If anyone could help me I would appreciate it! thx!

Was it helpful?

Solution

The way that bufferedReader works is that each line is parsed separately. That's what you are doing at String nextLine = br.readLine() - reading in a new line each time.

With your CSV file, you've only read in the first line - 2,. The reason you are getting a NoSuchElementException is that there is nothing else on that first line. The tokenizer cannot find anything else for the current string. You'll either have to change how you parse the input, or read in the next line before continuing.

OTHER TIPS

Syntax errors:

Integer.praseInt(st.nextToken());

....should be parse

for (int j=0 ....

missing ;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top