0

I am getting java.lang.NullPointerException and don't know exactly what is causing it. I know it has something to do with my getInput method, but I don't which line or lines is causing the error. Any help would be appreciated.

public class Input {

private Scanner scan;

//Checks input is an integer and bigger than 1
public int getInput() {
    String input = scan.next();
    int number = 0;
    boolean isNumber = true;

    while(isNumber) {
        try {
            number = Integer.parseInt(input);
            if(number >= 1) {
                isNumber = false;
            }
        } catch (NumberFormatException e) {
            isNumber = true;
            System.out.println("Error: please enter a whole number that is bigger than 1");
            input = scan.next();
        }
    }

    return number;

}

}

public class Main  {
public static void main (String[] args) {

    Input userInput = new Input();
    System.out.println("\t" +"Collatz Conjecture");
    System.out.println("Please enter a value: ");
    int n;
    n = userInput.getInput();

    System.out.println("Your number is " + n);
   }
}
Dooms
  • 25
  • 3
  • Are you initializing your scanner correctly? looks like you don't initialize it so it is null try adding `scan = new Scanner(System.in);` to the scanner class – Adam M. Mar 01 '18 at 20:23
  • My guess is that `scan` is `null` as you don't appear to be setting it. I would step through your code in your debugger to confirm this. – Peter Lawrey Mar 01 '18 at 20:24
  • First, duplicate; second, always add the stacktrace for those problems. The solution is almost always in it – AxelH Mar 01 '18 at 20:24
  • Clearly you haven't initialized the `scan` variable. – Juan Carlos Mendoza Mar 01 '18 at 20:26

1 Answers1

1

looks like you don't initialize it so it is null try adding scan = new Scanner(System.in); also you can use number = scan.nextInt();

Adam M.
  • 1,023
  • 1
  • 10
  • 21