gpt4 book ai didi

java - 尝试检查输入是否为整数时出现 java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-02 11:34:17 25 4
gpt4 key购买 nike

我收到 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);
}
}

最佳答案

看起来你没有初始化它,所以它是 null 尝试添加 scan = new Scanner(System.in);您也可以使用 number = scan.nextInt();

关于java - 尝试检查输入是否为整数时出现 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49058070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com