我收到了java.lang.NullPointerException,并且不知道究竟是什么导致了它。我知道它与我的getInput方法有关,但我不知道哪一行或多行导致错误。任何帮助,将不胜感激。
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);
}
}
答案 0 :(得分:1)
看起来你没有初始化它所以它为null尝试添加scan = new Scanner(System.in);
您也可以使用number = scan.nextInt();