0

I have 2 arrays->String [] Stops;String[][] fares;I want to pass them to a class object-> PostData.
But I get -> java.lang.NullPointerException: Attempt to write to null array. So, the alternative question is How to copy a 2D array so that contents point to same location

CODE:
PostData. java:

public class PostData {
    String url;
    String busNumber;
    int countStops;
    int countPairs;
    String [] Stops;
    String[][] fares;
    PostData(String urlArg, String  busNumberArg, int countStopsArg, int countPairsArg, String [] stopsArg, String[][] faresArg)
    {
        url = urlArg;
        busNumber = busNumberArg;
        countStops = countStopsArg;
        countPairs = countPairsArg;
        Stops = stopsArg;
        int c=0;
        for(String[] array:faresArg){
            fares[c++]=array;//null Pointer exception on this line
        }
    }
}

main:

PostData data = new PostData(stackServer, busNumber, count_stops, NumPairStops, Stops, fares);
   
a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
chinpin
  • 39
  • 4

1 Answers1

1

The problem that you didn't iniialize your fares array. You need to do something like this:

public class PostData {
    String url;
    String busNumber;
    int countStops;
    int countPairs;
    String [] Stops;
    String[][] fares;
    PostData(String urlArg, String  busNumberArg, int countStopsArg, int countPairsArg, String [] stopsArg, String[][] faresArg)
    {
        url = urlArg;
        busNumber = busNumberArg;
        countStops = countStopsArg;
        countPairs = countPairsArg;
        Stops = stopsArg;
        int c=0;
        fares = new String [faresArg.length][];
        for(String[] array:faresArg){
            fares[c++]=array;//null Pointer exception on this line
        }
    }
}
Alex Rmcf
  • 804
  • 7
  • 14