Am new to programming and am trying to create a system that is similar to a train timetable system.
I want the user to be able to enter the stops between two stations ( from a preset list of 5 stations ) and this be saved as an array list, and this array list be saved accordingly within a 2D array so if they were to look in [1][2] there would be an arraylist of stops between station 1 and 2.
I used this to initialise the array of arraylists (in a class i created called stops)
ArrayList<String>[][] stopsArray= (ArrayList<String>[][])new ArrayList[5][5]; public void stops(){ for (int i = 0; i<5; i++){ for (int j=0; j<5; j++){ stopsArray[i][j]= new ArrayList<String>(); } } }
Then I use this code to set the stops
The bottom written line of code is mentioned in the null pointer error I recievepublic void setNoStops(int stopsNo){ noOfStops = stopsNo; } public void setStops(int start, int end ){ for (int i=0; i< noOfStops ; i++){ System.out.println("Print Stop Number"+(i+1)+" :"); stopsArray[start][end].add(scanner.nextLine()); } }
Then in my main programme I declare the new object and use these methods
the method options displays the list of five stations with a number reference
System.out.println("Please choose a start station :"); options(); place1 = scanner.nextInt(); System.out.println(); System.out.println("Please choose an end station :"); options(); place2 = scanner.nextInt(); System.out.println(); System.out.println("Enter number of stops"); stopsno = scanner.nextInt(); mystops.setNoStops(stopsno); mystops.setStops(place1-1,place2-1);
mystops is the object I created to store the information.
when compiling I recieve no errors
when I run the program it runs smoothly, asks for the number of stops, allows the user to enter a number, then says enter stop 1, I enter a word and the program crashes giving the error java.lang.NullPointerException
can someone please explain where my program is going wrong?
thanks!