0

So this is my text file:

CareFlight101 0 2

PiperCub 2 99

AirAmbulance 2 1

TransWorld122 2 5

Cessna152 3 99

Eastern429 4 10

They are suppose to be aircrafts name followed my arrival time and landing priority.

I am trying to splitting it so that it takes each into account. I am having trouble splitting it though because it it throwing a 'java.lang.ArrayIndexOutOfBoundsException: 1' error This is what I have so far:

public class TheAircrafts {

    public static ArrayList<Plane> planeList;

    public static void main(String[] args){

        try {
            File f = new File("sample_data_p3.txt");
            Scanner sc = new Scanner(f);

            List<Plane> people = new ArrayList<Plane>();

            while(sc.hasNextLine()){
                String line = sc.nextLine();
                String[] details = line.split("\\s+");
                String flightID = details[0];
                int arrivalTime = Integer.parseInt(details[1]);
                int landingPriority = Integer.parseInt(details[2]);
                Plane p = new Plane(flightID, arrivalTime, landingPriority);
                planeList.add(p);
            }

            for(Plane p: planeList){
                System.out.println(p.toString());
            }

        } catch (FileNotFoundException e) {         
            e.printStackTrace();
        }
    }
}

And in my plane class I have:

public class Plane {

    private String flightID;
    private int arrivalTime;
    private int landingPriority;
    private int numRunways;


    public Plane(String flightID, int arrivalTime, int landingPriority) {
            this.setflightID(flightID); 
            this.arrivalTime = arrivalTime;
            this.landingPriority = landingPriority; 
    }

followed by get and set and get methods for each of the variables

ArK
  • 20,698
  • 67
  • 109
  • 136
Michelle
  • 61
  • 1
  • 2
  • 6
  • 2
    use `if (details.length==3) {` before reading flightId and other stuff. You should also debug this issue to see what is the input lne – TheLostMind Nov 17 '15 at 05:40

1 Answers1

0

You get a IndexOutOfBoundsException in this case when there is a line which not more than i elements seperated by a space.

In your case there is a line which has only one word in it. And hence when you try to get the second word which didn't exist you get an Exception.

To avoid getting so, you can check if that line has 3 words or not.

String []details = line.split("\\s+");
if(details.length == 3)
{
 //do your setting
}
Uma Kanth
  • 5,659
  • 2
  • 20
  • 41