我正在尝试构建一个只接受 int 作为有效答案的方法,一旦收到它就会返回它。
public class Application {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int usersInt = getIntInput();
}
public static int getIntInput(){
int userInt;
boolean success = false;
while (!success){
try {
userInt = sc.nextInt();
success = true;
} catch (Exception e){
System.out.println("Please type an int");
}
}
return userInt; // ERROR
}
}
我收到错误:
The local varaible userInt May not have been initialized.
我认为,直到用户输入一个 int 我们才会继续收到错误,success 不会收到 true,而 while 循环将继续提示用户输入一个 int。我的逻辑有问题吗?
最佳答案
您应该使用 Integer 类型而不是 int,然后您可以检查调用者中是否为 null,以查看是否输入了任何数字。然后,您可以将 getIntInput
中的 userInt
初始化为 null
。
public static void main(String[] args) {
Integer usersInt = getIntInput();
}
public static Integer getIntInput(){
Integer userInt = null; // Initialise the variable.
boolean success = false;
while (!success){
try {
userInt = sc.nextInt();
success = true;
} catch (Exception e){
sc.nextLine();
System.out.println("Please type an int");
}
}
return userInt;
}
关于java - 强制用户在 Java 中输入 int - 收到不清楚的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48759719/