强制用户在Java中键入int - 接收不清楚的错误

时间:2018-02-13 04:57:39

标签: java

我试图构建一个只接受int作为有效答案的方法,一旦收到它就返回它。

if (p_parent.parent('div').find('payment_status_' + orderID).click()) {
    if (process != '') {
        p_parent.parent('div').addClass('running');
    } else {
        p_parent.parent('div').removeClass('running');
    }
}
if (o_parent.parent('div').find('order_status_' + orderID).click()) {
    if (process != '') {
        o_parent.parent('div').addClass('running');
    } else {
        o_parent.parent('div').removeClass('running');
    }
}

我收到错误:

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
    }
}

我认为,在用户键入int之前,我们将继续收到错误,成功不会收到true,而while循环将继续提示用户键入int。我的逻辑有什么问题吗?

3 个答案:

答案 0 :(得分:1)

您应该使用Integer类型而不是int,然后您可以在调用者中检查是否为空,以查看是否输入了任何数字。然后,您可以将userInt中的getIntInput初始化为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;
}

答案 1 :(得分:1)

您的代码中唯一的问题是您使用的是未初始化的局部变量。

注意: Java编译器足够智能以确定userInt对象将在循环内初始化。

以下是一些纠正代码的选项:

  • 只需将行int userInt;更改为int userInt = 0;,然后在sc.nextLine();中添加行sc.next()catch-block(至 flush stdin < / em>,否则它将进入无限循环打印消息Please type an int)。
  • 按以下方式更改您的代码:

    public class Application {
        static Scanner sc = new Scanner(System.in);
    
        public static void main(String[] args) {
            int usersInt = getIntInput();
    
        }
    
        public static int getIntInput(){
            while (true){
                try {
                    return sc.nextInt();
                } catch (Exception e){
                    System.out.println("Please type an int");
                    sc.nextLine();
                }
            } 
        }
    }
    

答案 2 :(得分:0)

您正在while循环之外初始化userInt变量,并在循环内初始化它的值。就编译器而言,循环可能不会运行,并且在函数调用结束时返回时,userInt可能不会被赋予值。因此它会抛出错误&#34;本地变量userInt可能尚未初始化&#34;试图帮助您找到可能导致用户对该程序出现问题的潜在错误。

使用默认值初始化变量当然有帮助,但也可以通过阻止该值用作输入来限制输入。如果该值自然受限,并且该限制不包括您用于存储该值的二进制表示的最小值和最大值,则可以将该范围外的值用作默认值。例如,当没有给出输入时,需要用户输入1或更高的数字,并使用0作为默认值。

如果您确实需要整个值范围,则可以使用布尔标志并返回它和用户的输入值。然后在处理程序中,当您从用户那里获得输入时,根据需要设置标志并在调用函数中测试以查看是否收到了用户输入。