0

What is causing my error???

public class Keyboard {
    private Scanner keyboard;

    /**
     * Default contructor
     */
    public void keyboard() {
        keyboard = new Scanner(System.in);
    }

    /**
     * get and return an int
     * @return an int
     */
    public int getInt() {
        int myInt;
        myInt = keyboard.nextInt();
        keyboard.nextLine();

        return myInt;
    }
}

public class TestKeyboard {
    public static void main(String[] args) {
        System.out.println("enter an int: ");
        Keyboard keyboard = new Keyboard();
        keyboard.getInt();
    }
}

I am currently getting the following exception:

java.lang.NullPointerException at Keyboard.getInt(Keyboard.java:27) at TestKeyboard.main(TestKeyboard.java:6)

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
Bobby
  • 21
  • 3
  • `keyboard` (the `Scanner`) is `null`. You seem to have mistaken the constructor for a method `public void keyboard() {` probably should be `public Keyboard() {` – MadProgrammer Sep 25 '15 at 03:16
  • @MadProgrammer Did you bother to read any of the answers given below, which answered the question before you marked as duplicate? – Tim Biegeleisen Sep 25 '15 at 03:18
  • @TimBiegeleisen Yes, I did, and the question should have been marked as a duplicate earlier, as we don't need to contently keep answering `NullPointerException` questions, but should be encouraging developers to develop good debugging skills instead. This question has been answered before and doesn't/shouldn't be answered again (and don't get me started on my opinion of the answer) – MadProgrammer Sep 25 '15 at 03:21
  • I agree with you, but because so much time elapsed and no moderator marked as a duplicate, I decided to answer it (q.v. below). In any case, in a few months I will have some admin rights, then I will also be able to do this. – Tim Biegeleisen Sep 25 '15 at 03:23
  • @TimBiegeleisen You should be able to "vote to close" now, but I think you need +100K to "hammer" close (not my favorite power by the way) – MadProgrammer Sep 25 '15 at 04:00
  • Rats...I'm about 2-3 years out from breaking 100K. By then, half the planet will have a rep of 100K :-( – Tim Biegeleisen Sep 25 '15 at 04:26

1 Answers1

0

There is no default constructor . The constructor should be public KeyBoard(). The Keyboard class has a keyboard() method that you are considering as constructor.

Nikita Shrivastava
  • 2,978
  • 10
  • 20