java - 强制用户在 Java 中输入 int - 收到不清楚的错误

标签 java

我正在尝试构建一个只接受 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/

相关文章:

java - 如何以编程方式获取特定 JVM 实例的系统属性?

java - 如何从java中的图像获取轮廓路径?

java - Java 中是否可以将数字数据类型转换为字符串输出?

java - 使用 Java API 的 ElasticSearch 全文搜索

java - Jaybird/JDBC + 路径中的国家字符

java - 餐厅菜单 : how to efficiently implement a nested loop to collect user input and conduct error checking

java - 如何使用 JSF 2.0 显示浏览器名称和版本?

java - 数据流 GZIP TextIO ZipException : too many length or distance symbols

java - 在后台下载并解压 zip 文件?

java - Spring Boot 删除额外的 HealthIndicator 信息