使用If检查整数

时间:2018-04-20 20:32:18

标签: java

如何使用If检查输入必须是整数且不能输入任何英文单词。

int numWeight = sc.nextInt();
if (numWeight == (int)numWeight) {
    ((Salad)menu[itemNum - 1]).setWeight(numWeight);

    System.out.println(menu[itemNum - 1].showOrderDetails());
    System.out.println("-------------------------------------------");
    System.out.println("Total No. of items ordered :");

    orderedItem[TtlOrderNum] = menu[itemNum - 1];
    TtlOrderNum += 1;

    Continue();
}
else {
    System.out.println("input must a be integer");
}

当我使用此代码运行它并输入整数时,它会显示:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at SaladAndDrinkOrderSystem.placeOrder(SaladAndDrinkOrderSystem.java:69)
    at TestSaladAndDrinkOrderSystem.main(TestSaladAndDrinkOrderSystem.java:23)

2 个答案:

答案 0 :(得分:1)

您需要执行以下操作:

int numweight;
try {
    numweight = sc.nextInt();
    // Rest of your code here...
} catch (InputMismatchException e) {
    System.err.println("Please enter an integer");
}

为了不让java抛出输入不匹配异常。

答案 1 :(得分:0)

请注意,如果您将非Integer值传递给numWeight,则会引发输入错误匹配异常cannot convert from xxxx to int,因此在我看来,您可以使用try-catch假设您将接收一个int,如果你没有收到它,catch会打印给你,它必须是一个Integer,如下所示:

    int numWeight;
    try {
        numWeight = sc.nextInt();       
        ((Salad)menu[itemNum - 1]).setWeight(numWeight);

        System.out.println(menu[itemNum - 1].showOrderDetails());
        System.out.println("-------------------------------------------");
        System.out.println("Total No. of items ordered :");

        orderedItem[TtlOrderNum] = menu[itemNum - 1];
        TtlOrderNum += 1;

        Continue();
    }
    catch(InputMismatchException e) {
         System.err.println("Input must be an Integer");
    }

这样,如果sc.nextInt()不是整数,你将打印错误,说它可能是。

但是,如果你想保持原来的检查想法是值是一个整数,你可以使用instaceof运算符,这样的东西

    Integer numWeight = sc.nextInt();
    if (numWeight instanceof Integer) {
        ((Salad)menu[itemNum - 1]).setWeight(numWeight);

        System.out.println(menu[itemNum - 1].showOrderDetails());
        System.out.println("-------------------------------------------");
        System.out.println("Total No. of items ordered :");

        orderedItem[TtlOrderNum] = menu[itemNum - 1];
        TtlOrderNum += 1;

        Continue();
    }
    else {
        System.out.println("input must a be integer");
    }   

请记住,如果您选择第二种方法,如果st.nextInt()不是int,则会引发异常。