This site requires JavaScript, please enable it in your browser!
Greenfoot back
rockon411
rockon411 wrote ...

2017/4/3

Null Pointer Exception

rockon411 rockon411

2017/4/3

#
I have a code that seems to run fine, but when I submit it the program is picking up on a null pointer exception in line 14. I only have a understanding of what the means, so any explanation or help would be greatly appreciated.
private Scanner input;
public RemoteTux()
    {
        IOHelper.createScannerForURL(
      "http://courses.cs.vt.edu/~cs1114/Fall2012/tux-commands.txt");
    }
public RemoteTux(Scanner scanner)
    {
        this();
        input = scanner;
    }
public void act()
    {
        if (input.hasNext())
        {
            String command = (String)input.next();
            if ("left".equals(command))
            {
                left();
            }
            else if ("right".equals(command))
            {
                right();
            }
            else if ("forward".equals(command))
            {
                forward();
            }
        }
    }
Super_Hippo Super_Hippo

2017/4/3

#
rockon411 wrote...
I only have a understanding of what the means
Not sure if I understand what you mean by that, but the problem with the code is that when ever a RemoteTux is created with 'new RemoteTux()' and added to the world, you will get the NullPointer exeption. The reason is that the Scanner variable 'input' (created in line 1) is never assigned to a Scanner object. That is only happening when the RemoteTux object is created with the second constructor.
danpost danpost

2017/4/3

#
I get the feeling that line 4 should start with 'input = '.
rockon411 rockon411

2017/4/3

#
Thanks guys! That helped a lot!
You need to login to post a reply.