array elements are null outside loop

so I’ve been trying to make an array of (flight)objects (a class i made that's mainly accessors and mutators) and my first problem is that if I try to print out the elements of the array outside the loop i get a null pointer exception

my second problem is that i’m reading the flights from an input file and whenever it makes a flight object and I try to invoke an accessor method or any other method from the flight class for example(getCity) it gives me the cities for all the other flights from like other lines (each line is a command) I hope the code clarifies my question more:

  //flight adding method
                 public static Flight addFlight(String[] array){
           
               Flight flight =new Flight(array[1], array[2],array[3], 
    Integer.parseInt(array[4]),Integer.parseInt(array[5]), 
    Double.parseDouble(array[6]));
              
              return flight;
                 }

Main:

   Flight[]  flights= new Flight[findSpecifiedLine(0,inputFlight)];
      while(input.hasNext()){
          String line=""; 
          int i=0;
          line = input.nextLine();  
          
          
          String []arrays=line.split("\\s+");
            
             if((arrays[0].equalsIgnoreCase("Add_Flight"))){
                
                 if(((Flight.getindexFlight()<=findSpecifiedLine(0,inputFlight)))){
                 for(int j=0;j<flights.length;j++){
                  flights[j]=addFlight(arrays);
                 }
                  Flight.incindexFlight();
                 }
                 else{
                          System.out.println("can't add flight");
                          break;
                         }
                 
                System.out.print(flights[1].getCityTo());
             }

             
      }
    
    input.close();
    output.close();  

some of the input from the txt file

Add_Flight SA760 Paris London 868 10 4500

Add_Flight SA222 Munich London 868 10 4500 System.out.print(flights[0].getCityFrom()); }

would print ParisMunich instead of only Paris as it's supposed to

Posted Mar 12, 2018, 9:51 PM UTC

11
Loading comments…