Results 1 to 8 of 8
Like Tree1Likes
  • 1 Post By pbrockway2

Thread: Why am I getting a NullPointerException?

  1. #1
    atac57 is offline Member
    Join Date
    Jan 2012
    Posts
    24
    Rep Power
    0

    Default Why am I getting a NullPointerException?

    I'm making a Battleship game and I'm using the nextLine() method to enter a letter coordinate, but I'm getting an exception. This is just the code for the class containing the main method. I'm not seeing what the reason for this is, any help? Thanks.

    Java Code:
    public class Simulation1 {
    	public static final int BOARD_SIZE = 10;
    	public static final int BATTLESHIP_NOT_PLACED = 0;
    	public static final int BATTLESHIP_PLACED = 1;
    	public static final int MISS = 2;
    	public static final int HIT = 3;
    	public static final int NUMBER_OF_SHIPS = 3;
    	public static Random random;
    	public static Scanner scanner;
    	
    	public static void main(String[] args) {
    		int board[][] = new int[BOARD_SIZE][BOARD_SIZE];
    		Battleship battleship = new Battleship(board);
    		battleship.initializeBoard();
    		battleship.placeShips();
    		battleship.printBoard();
    		battleship.printDebugBoard();
    		
    		System.out.println();
    		System.out.println("Enter letter coordinate: ");
    		String letter = scanner.nextLine(); //<---- NullPointerException
    		
    		System.out.println("Enter number coordinate: ");
    		int number = scanner.nextInt();
    
    	}
    }

  2. #2
    awinston is offline Student
    Join Date
    Jul 2012
    Location
    United States
    Posts
    328
    Rep Power
    2

    Default Re: Why am I getting a NullPointerException?

    You didn't initialize the variable scanner to reference a Scanner object. See comments in code for details.


    Quote Originally Posted by atac57 View Post
    Java Code:
    public class Simulation1 {
    	public static final int BOARD_SIZE = 10;
    	public static final int BATTLESHIP_NOT_PLACED = 0;
    	public static final int BATTLESHIP_PLACED = 1;
    	public static final int MISS = 2;
    	public static final int HIT = 3;
    	public static final int NUMBER_OF_SHIPS = 3;
    	public static Random random;
    	public static Scanner scanner;                                                    //scanner variable is never initialized to reference a Scanner object
    	
    	public static void main(String[] args) {
    		int board[][] = new int[BOARD_SIZE][BOARD_SIZE];
    		Battleship battleship = new Battleship(board);
    		battleship.initializeBoard();
    		battleship.placeShips();
    		battleship.printBoard();
    		battleship.printDebugBoard();
    		
    		System.out.println();
    		System.out.println("Enter letter coordinate: ");
    		String letter = scanner.nextLine(); //<---- NullPointerException              //a method is called on a variable that references null, so NullPointerException is thrown
    		
    		System.out.println("Enter number coordinate: ");
    		int number = scanner.nextInt();                                               //same here, but technically this code wasn't reached.
    
    	}
    }
    "Success is not final, failure is not fatal: it is the courage to continue that counts." - Winston Churchill

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Why am I getting a NullPointerException?

    You get a NullPointerException when you use a variable, or other expression, as if it had a non null value when it, in fact has the value null. Two common places you might do this are arrays and using the "dot" operator to invoke methods:

    Java Code:
    String[] arr;
    arr[0] = "foo"; // Bad! arr is null
    
    arr = new String[42];
    System.out.println(arr[0].length()); // Bad! arr[0] is null
    
    String foo;
    System.out.println(foo.length()); // Bad! foo is null
    The first thing to do is look at the line where the NPE is reported and try to figure out what is null.

    Java Code:
    String letter = scanner.nextLine(); //<---- NullPointerException
    There are not a lot of choices here! It looks like the culprit is scanner. You can check this by printing out its value:


    Java Code:
    System.out.println("About to read a line, scanner=" + scanner);
    String letter = scanner.nextLine(); //<---- NullPointerException
    If it turns out that scanner is indeed null you ought to go back through your code to where you thought you had given scanner a non null value and figure out why that didn't happen. (Or if you just plain forgot to initialise scanner then do that: assign scanner a non null value.)

  4. #4
    atac57 is offline Member
    Join Date
    Jan 2012
    Posts
    24
    Rep Power
    0

    Default Re: Why am I getting a NullPointerException?

    Ahhh, I knew it was something simple! Thank you both. Quick question, I'm still somewhat new to Java and I'm trying to practice good habits. I was told that instantiating an object in the field of a class is bad practice. Is that correct? I think I forgot that because I'm typically used to declaring and instantiating an object all in one line.

    Java Code:
    public class Simulation1 {
        public static final int BOARD_SIZE = 10;
        public static final int BATTLESHIP_NOT_PLACED = 0;
        public static final int BATTLESHIP_PLACED = 1;
        public static final int MISS = 2;
        public static final int HIT = 3;
        public static final int NUMBER_OF_SHIPS = 3;
        public static Random random;
        public static Scanner scanner = new Scanner(System.in); <--- bad?

  5. #5
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Why am I getting a NullPointerException?

    I was told that instantiating an object in the field of a class is bad practice. Is that correct?
    The problem - as I see it - is exactly the problem you have run in to: if you forget to initialise a variable, or inadvertently reinitialise it, or can't easily figure out *what* you initialised it to (and where), then there is the scope for bugs.

    I'm suspicious of "practices" if the intention is that we slavishly follow the good and shun the bad. It would have been an easy matter for Java's designers to simply forbid scanner being initialised the way you have it if they had wanted to. What's needed are principles (from which the goodness of the practices follows) and, in this case, the principle is clarity. It ought to be clear from the code where variables are initialised and to what.

    You don't ask but I think initialising the "constants" the way you do is perfectly clear.

    As for scanner I prefer fields (instance variables) to be initialised in a constructor. (But am happy not to if something else is clearer in a given context). In your code, however, you are not really using classes except in a formal sense. scanner is a static variable. And there is no constructor that is ever used.

    So... In the general case I would use classes and avoid static variables altogether and I would initialise the variables in constructors. (And I would defend, or change, that practice as dictated by clarity). But in your case - a static variable in a class which doesn't seem designed to be instantiated - I think what you've done is as clear as it could be.
    Last edited by pbrockway2; 07-28-2012 at 06:01 AM.
    awinston likes this.

  6. #6
    awinston is offline Student
    Join Date
    Jul 2012
    Location
    United States
    Posts
    328
    Rep Power
    2

    Default Re: Why am I getting a NullPointerException?

    I also think it's recommended to use a static block in order to initialize static fields: Initializing Fields (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
    Last edited by awinston; 07-28-2012 at 06:18 AM. Reason: grammar
    "Success is not final, failure is not fatal: it is the courage to continue that counts." - Winston Churchill

  7. #7
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default Re: Why am I getting a NullPointerException?

    A static block is only required if the field initialization can throw an Exception, for which you can nest a try/catch[/finally] block inside the static initializer.

    I don't think it would make sense to lump assignment statements inside a static block where simple declaration-cum-assignment statements would suffice.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  8. #8
    awinston is offline Student
    Join Date
    Jul 2012
    Location
    United States
    Posts
    328
    Rep Power
    2

    Default Re: Why am I getting a NullPointerException?

    Thanks for the clarification, db.
    "Success is not final, failure is not fatal: it is the courage to continue that counts." - Winston Churchill

Similar Threads

  1. NullPointerException
    By JG4m3r in forum New To Java
    Replies: 2
    Last Post: 05-16-2012, 06:36 PM
  2. NullPointerException
    By Mate de Vita in forum New To Java
    Replies: 52
    Last Post: 03-22-2012, 11:27 AM
  3. NullPointerException
    By s0meb0dy in forum New To Java
    Replies: 3
    Last Post: 10-09-2010, 08:12 PM
  4. NullPointerException
    By sanu in forum Java Applets
    Replies: 3
    Last Post: 08-21-2010, 08:37 PM
  5. NullPointerException
    By speedzojie@gmail.com in forum New To Java
    Replies: 5
    Last Post: 06-03-2010, 05:39 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •