Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 19 of 19

Thread: Can't read into Array List.

  1. #1
    Junior Member
    Join Date
    Apr 2014
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Can't read into Array List.

    Hi, First time poster here so sorry if I've done something wrong in relation to posting. I am creating a hangman game and I want to read in a list of words from a text file, but after the user inputs the name of the text file. I get 'Exception in thread "main" java.lang.NullPointerException'.

    Here is the code, where I think the problems lie.

    	public void runModel(){
    		ArrayList<String> pirateWordsList = new ArrayList<String>();
    		System.out.println("What is the name of the file you would like to load? (The file included is called  piratewords.txt'");
    		Scanner in=new Scanner(System.in);
    		String file=in.next();
    		load(file);
    		System.out.println(pirateWordsList);
     
    	 public void load(String pirate){
    	        Scanner infile;
    			try {
    				infile = new Scanner(new InputStreamReader
    				(new FileInputStream(pirate)));
    				 int num=infile.nextInt();infile.nextLine();
    			        for (int i=0;i<num;i++){
    			           String secretPirateWord=infile.nextLine();
    			            pirateWordsList.add(secretPirateWord);
    			        }
    			        infile.close();
    			} 
    			catch (FileNotFoundException e) {
    				System.out.println("File not found, are you sure you entered the files name correctly and is the file in the correct directory");
    			}
     
    }
    The full error message is this:
    Exception in thread "main" java.lang.NullPointerException
    at uk.ac.aber.dcs.pirate_hangman.Model.load(Model.jav a:108)
    at uk.ac.aber.dcs.pirate_hangman.Model.runModel(Model .java:45)
    at uk.ac.aber.dcs.pirate_hangman.Main.main(Main.java: 6)
    Last edited by BouncySean; April 5th, 2014 at 09:33 AM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Can't read into Array List.

    Please edit your post and wrap your code with code tags:
    [code=java]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.

    java.lang.NullPointerException
    Look at the line of code mentioned in the error message and find the variable with the null value. Then backtrack in the code to see why that variable has a null value.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Can't read into Array List.

    Welcome to the forum! Please read this topic to learn how to post code in code or highlight tags and other useful info for new members.

    Just typical first-time poster things. No worries.

    So, post your code correctly as described in the above link, and when you're done with that, please post the entire error message. It includes details you haven't provided. Pointing those useful details out to you will help you interpret the messages and determine a fix (or possible fixes) on your own.

  4. #4
    Junior Member
    Join Date
    Apr 2014
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't read into Array List.

    Quote Originally Posted by Norm View Post
    Please edit your post and wrap your code with code tags:
    [code=java]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.


    Look at the line of code mentioned in the error message and find the variable with the null value. Then backtrack in the code to see why that variable has a null value.
    Quote Originally Posted by GregBrannon View Post
    Welcome to the forum! Please read this topic to learn how to post code in code or highlight tags and other useful info for new members.

    Just typical first-time poster things. No worries.

    So, post your code correctly as described in the above link, and when you're done with that, please post the entire error message. It includes details you haven't provided. Pointing those useful details out to you will help you interpret the messages and determine a fix (or possible fixes) on your own.
    Hi thanks a lot guys, I've edited the post now.
    I did try looking at where the null pointer was thrown but I can't figure the problem out.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Can't read into Array List.

    Exception in thread "main" java.lang.NullPointerException
    at uk.ac.aber.dcs.pirate_hangman.Model.load(Model.jav a:108)
    Look at line 108. What variable on that line has a null value when it is executed?
    Use a println() to print the values of all the variables used on line 108 if you can't tell which is null.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Apr 2014
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't read into Array List.

    Quote Originally Posted by Norm View Post
    Look at line 108. What variable on that line has a null value when it is executed?
    Use a println() to print the values of all the variables used on line 108 if you can't tell which is null.
    The only thing with a value on line 108 with a value of 0 is i, as line 108 is the for (int i=0;i<num;i++){ line. I have checked num prints out 7 and i prints out 0, also the array list is empty as this point which is what I would expect.

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Can't read into Array List.

    You can't be looking at the correct line if this is the line at 108:
    for (int i=0;i<num;i++){

    There aren't any object references on that line. You do not get the NullPointerException with a primitive like an int.

    NOTE: the value of 0 in an primitive is NOT the same as the value of null in an object reference variable.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Apr 2014
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't read into Array List.

    Quote Originally Posted by Norm View Post
    You can't be looking at the correct line if this is the line at 108:
    for (int i=0;i<num;i++){

    There aren't any object references on that line. You do not get the NullPointerException with a primitive like an int.

    NOTE: the value of 0 in an primitive is NOT the same as the value of null in an object reference variable.
    Sorry I altered the code and that messed up the lines.
    The error is happening at this line: pirateWordsList.add(secretPirateWord);
    I sucesfully printed out the secrretPirateWord however when I tried to print out the arrayList before the load it gave me [] as I would expect but after the load it gave me nothing at all not even the value null.

  9. #9
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Can't read into Array List.

    Notice also that the last item on the stack before the error message is:

    at uk.ac.aber.dcs.pirate_hangman.Model.load(Model.jav a:108)

    which indicates that the load() method call is experiencing the null. Therefore, check this line:

    load(file);

    to determine why 'file' is null.

    Edit: Or, with the line numbering confusion, why the call to load() contains a null argument from wherever it's being called.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Can't read into Array List.

    The error is happening at this line: pirateWordsList.add(secretPirateWord);
    There are two variables on that line.
    pirateWordsList
    secretPirateWord
    What are their values?
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Apr 2014
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't read into Array List.

    Quote Originally Posted by Norm View Post
    There are two variables on that line.
    pirateWordsList
    secretPirateWord
    What are their values?
    Null for both variables.

    --- Update ---

    Quote Originally Posted by GregBrannon View Post
    Notice also that the last item on the stack before the error message is:

    at uk.ac.aber.dcs.pirate_hangman.Model.load(Model.jav a:108)

    which indicates that the load() method call is experiencing the null. Therefore, check this line:

    load(file);

    to determine why 'file' is null.

    Edit: Or, with the line numbering confusion, why the call to load() contains a null argument from wherever it's being called.
    I've tested the load and it defiantly is picking up the txt files name correctly.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Can't read into Array List.

    Null for both variables.
    Why is the variable for the ArrayList null? Look at where that variable is given a value. Make sure that there is NOT another variable defined that is "shadowing" the class level variable.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Apr 2014
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't read into Array List.

    Quote Originally Posted by Norm View Post
    Why is the variable for the ArrayList null? Look at where that variable is given a value. Make sure that there is NOT another variable defined that is "shadowing" the class level variable.
    Okay I will check now.

    --- Update ---

    The error definatly appears to happen when I add the words to the array.
    I have added some test code as shown below, and I have put the output below that:

    public void runModel(){
    		ArrayList<String>pirateWordsList = new ArrayList<String>();
    		System.out.println(pirateWordsList);
    		System.out.println("What is the name of the file you would like to load? (The file included is called  piratewords.txt'");
    		Scanner in=new Scanner(System.in);
    		String file=in.next();
    		System.out.println(file);
    		load(file);
    		System.out.println(pirateWordsList);
    	    System.out.println(secretPirateWord);
    	    in.close();
    	}
     
    public void load(String pirate){
    	        Scanner infile;
    			try {
    				infile = new Scanner(new InputStreamReader
    				(new FileInputStream(pirate)));
    				 int num=infile.nextInt();infile.nextLine();
    			        for (int i=0;i<num;i++){
    			           String secretPirateWord=infile.nextLine();
    			           System.out.println(secretPirateWord);
    			           System.out.println(pirateWordsList);
    			            pirateWordsList.add(secretPirateWord);
    			            System.out.println(secretPirateWord);
    			        }
    			        infile.close();
     
    			} 
    			catch (FileNotFoundException e) {
    				System.out.println("File not found, are you sure you entered the files name correctly and is the file in the correct directory");
    			}
     
    }

    The output from in response to that code is:
    []
    What is the name of the file you would like to load? (The file included is called piratewords.txt'
    piratewords.txt
    piratewords.txt
    ahoy there
    null
    Exception in thread "main" java.lang.NullPointerException
    at uk.ac.aber.dcs.pirate_hangman.Model.load(Model.jav a:116)
    at uk.ac.aber.dcs.pirate_hangman.Model.runModel(Model .java:48)
    at uk.ac.aber.dcs.pirate_hangman.Main.main(Main.java: 6)
    Last edited by BouncySean; April 5th, 2014 at 12:10 PM.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Can't read into Array List.

    Why is the variable: pirateWordsList null? Look at where that variable is given a value. Make sure that there is NOT another variable defined that is "shadowing" the class level variable.
    Is pirateWordsList defined in more than one place?
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Apr 2014
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't read into Array List.

    Quote Originally Posted by Norm View Post
    Why is the variable: pirateWordsList null? Look at where that variable is given a value. Make sure that there is NOT another variable defined that is "shadowing" the class level variable.
    Is pirateWordsList defined in more than one place?
    I'm going to check now, and will type in the code where pirateWordsList is defined/used.[COLOR="Silver"]

    --- Update ---

    I first of all defined pirateWordList as an instance variable:
    ArrayList<String> pirateWordsList ;
    //other instance variables etc.


    I then initalise it in the runModel class it :
    public void runModel(){
    		ArrayList<String>pirateWordsList = new ArrayList<String>();
    //rest of runModel code.

    And then the only other time I mention it is in my load method:

     
    	 public void load(String pirate){
    	        Scanner infile;
    			try {
    				infile = new Scanner(new InputStreamReader
    				(new FileInputStream(pirate)));
    				 int num=infile.nextInt();infile.nextLine();
    			        for (int i=0;i<num;i++){
    			           String secretPirateWord=infile.nextLine();
    			           System.out.println(secretPirateWord);
    			           System.out.println(pirateWordsList);
    			            pirateWordsList.add(secretPirateWord);
    			            System.out.println(secretPirateWord);
    			        }
    			        infile.close();

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Can't read into Array List.

    It looks like the code NEVER assigns a value to the class instance variable. The class instance variable is what is used in the load() method. but its value is null.
    The local variable defined in runModel() is a different variable from the class instance variable. It "shadows" or hides the class instance variable.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Junior Member
    Join Date
    Apr 2014
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't read into Array List.

    Quote Originally Posted by Norm View Post
    It looks like the code NEVER assigns a value to the class instance variable. The class instance variable is what is used in the load() method. but its value is null.
    The local variable defined in runModel() is a different variable from the class instance variable. It "shadows" or hides the class instance variable.
    Okay well I tried to solve that my actually placing the load method in the runModel but have still had no joy. Do you have any suggestions please?

    --- Update ---

    I now altered it by actually initialising the Array List when it's being declared as an instance variable(I know that technically goes against the stanrads but I done it for test puproses) and I got these errors:
    Exception in thread "main" java.lang.IllegalStateException: Scanner closed
    at java.util.Scanner.ensureOpen(Scanner.java:1115)
    at java.util.Scanner.findWithinHorizon(Scanner.java:1 713)
    at java.util.Scanner.nextLine(Scanner.java:1583)
    at uk.ac.aber.dcs.pirate_hangman.Model.load(Model.jav a:113)
    at uk.ac.aber.dcs.pirate_hangman.Model.runModel(Model .java:47)
    at uk.ac.aber.dcs.pirate_hangman.Main.main(Main.java: 6)
    Last edited by BouncySean; April 5th, 2014 at 12:53 PM.

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Can't read into Array List.

    Do you have any suggestions
    Define the variable in ONE place at the class level and
    either assign it a value where it is defined
    or assign it a value in a method.
    Do NOT define variables with the same name in a method as is defined at the class level.

    Exception in thread "main" java.lang.IllegalStateException: Scanner closed
    at java.util.Scanner.ensureOpen(Scanner.java:1115)
    at java.util.Scanner.findWithinHorizon(Scanner.java:1 713)
    at java.util.Scanner.nextLine(Scanner.java:1583)
    at uk.ac.aber.dcs.pirate_hangman.Model.load(Model.jav a:113)
    The code at line 113 called the nextLine() method after the Scanner object has been closed.
    Don't close the Scanner until the program is done using it.
    If you don't understand my answer, don't ignore it, ask a question.

  19. #19
    Junior Member
    Join Date
    Apr 2014
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't read into Array List.

    Quote Originally Posted by Norm View Post
    Define the variable in ONE place at the class level and
    either assign it a value where it is defined
    or assign it a value in a method.
    Do NOT define variables with the same name in a method as is defined at the class level.


    The code at line 113 called the nextLine() method after the Scanner object has been closed.
    Don't close the Scanner until the program is done using it.
    Thank you so much everything works perfectly now

Similar Threads

  1. [SOLVED] Read String to List<Integer> and back
    By Cornix in forum Java Theory & Questions
    Replies: 2
    Last Post: February 14th, 2014, 07:15 PM
  2. Converting Two dimensional array into an Array list
    By NewbieJavaProgrammer in forum Object Oriented Programming
    Replies: 11
    Last Post: September 29th, 2012, 04:23 PM
  3. Contain method to read array
    By theaveguy in forum Loops & Control Statements
    Replies: 3
    Last Post: February 27th, 2012, 12:32 AM
  4. Contain method to read array
    By theaveguy in forum Java Theory & Questions
    Replies: 8
    Last Post: February 25th, 2012, 02:53 PM
  5. Array List of Array Lists working for first item but not for second.
    By javapenguin in forum Collections and Generics
    Replies: 6
    Last Post: February 15th, 2012, 05:12 PM