简体   繁体   中英

Why am I getting an Array Index Out Of Bounds Exception error when parsing lines?

In netbeans I got an Array Index Out Of Bounds Exception error in my code at line 35 in the MyProj03 class from line 55 in the Person class. I am not sure why I am getting this error.

My code:

import java.util.Scanner;
import java.io.*;
import birch.Person.*;



public class MyProj03 {

    public static void main(String[] args) throws IOException {
        // check for file existence
        File file = new File("p3text.txt");
        if (file.exists())
        {
       // read each record into a String
            StringBuilder fileContents = new StringBuilder((int)file.length());
            Scanner scanner = new Scanner("p3text.txt");
            String lineSeparator = System.getProperty("line.separator");

            try {
                while(scanner.hasNextLine()) { 
                    fileContents.append(scanner.nextLine() + lineSeparator);
                    Person one = new Person();
                    one.parseCommaDelim(fileContents.toString());
            }

            } finally 
            {
                scanner.close();
            }
        }
        else if (!file.exists())
        {
            System.out.println("The file p3text.txt is not found.");
            System.exit(2);
        }





        }
}

more code:

public class Person {

     //make instance fields for name, city, age, and SiblingCount
       public String name;

       public int age;

       public String city;

       public int sibCount; 

       public Person()
       {
        name = "";
        age = 0;
        city = "";
        sibCount = 0;
       }

       // public access methods (getters)
       public String getPerson() {
       return this.name;
       }

       public int getAge() {
       return this.age;
       }

       public String getCity() {
       return this.city;
       }

       public int getSibCount() {
       return this.sibCount;
       }



    // make a toString method
   public String toString()
   {
       String str = "person: " + name + "age: " + age + "city: " + city;
       return str;
   }
   // make a method called parseCommaDelim
   public Person parseCommaDelim(String s) {
        String[] tokens = s.split(",");

        Person instance = new Person();
        instance.name = tokens[0];
        instance.age = Integer.parseInt(tokens[1]); //ArrayIndexOutOfBoundsException error 
        instance.city = tokens[2];
        instance.sibCount = Integer.parseInt(tokens[3]);

return instance;
}

   public int getIndex(Arrays list[], String key)
   {

   for (int index = 0; index< list.length; index++)
    {
     if ( list[index].equals(key) ) 
     return index;  
    }
       return -1;
   }

}

My text file

Rhonda, 20 , San Diego , 1
Kaitlin, 24 , Provo , 4
Bret, 24 , Columbia , 4
Chris, 28 , Escondido , 2
Dylan, 21, Portland, 3

You should replace

Person one = new Person();
one.parseCommaDelim(lineSeparator);

with

Person one = new Person();
one.parseCommaDelim(fileContents.toString());

as your current implementation tries to parse the , itself, not the string your read.

You can scan file's content line by line and process with this code:

public class MyProj03 {

public static void main(String[] args) throws IOException {
File file = new File("p3text.txt");

try {
    Scanner scanner = new Scanner(file);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        Person one = new Person();
        one.parseCommaDelim(line);
    }
    scanner.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
}

also I recommend you to change the fragment codes :

    Person instance = new Person();
    instance.name = tokens[0];
    instance.age = Integer.parseInt(tokens[1]); //ArrayIndexOutOfBoundsException error 
    instance.city = tokens[2];
    instance.sibCount = Integer.parseInt(tokens[3]);

to this:

   Person instance = new Person();
   instance.name = tokens[0];
   instance.age = Integer.parseInt(tokens[1].trim()); //ArrayIndexOutOfBoundsException error 
   instance.city = tokens[2];
   instance.sibCount = Integer.parseInt(tokens[3].trim());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM