如何正确嵌套此If语句

时间:2020-02-18 06:15:20

标签: java if-statement

我正在捕获用户输入,但将其限制在1-100之间。我在正确嵌套此if语句时遇到了一些困难。 目标: 用户可以输入1-100之间的任意数量 如果不是,它将自动设置为0。 我在最后打印结果

    // if statement to restrict use to 1-100
    hatNumber = in.readInt("How many beaver hats would you like?: \n");
    if (hatNumber <= 0 && hatNumber > 100) {
        System.out.println("Hats = " + hatNumber);
    } else {
        hatNumber = 0;
    }
    photoNumber = in.readInt("How many photographs would you like?: \n");
    if (photoNumber <= 0 && photoNumber > 100) {
        System.out.println("Photographs = " + photoNumber);
    } else {
        photoNumber = 0;

        jarNumber = in.readInt("How many Jars of maple syrup?: \n");



    if (jarNumber <= 0 && jarNumber > 100) {
            System.out.println("Jars = " + jarNumber);

        } else {
            jarNumber = 0;
            {

                System.out.println("Hats = " + hatNumber);
                System.out.println("Photographs = " + photoNumber);
                System.out.println("Jars = " + jarNumber);

3 个答案:

答案 0 :(得分:1)

首先,如果期望逻辑“用户可以输入1-100之间的任何数量,否则将自动设置为0”。如果没有,请更改

if (hatNumber > 0 && hatNumber <= 100) {
        System.out.println("Hats = " + hatNumber);
} else {
        hatNumber = 0;
}

最终代码如下。

    hatNumber = in.readInt("How many beaver hats would you like?: \n");
    if (hatNumber > 0 && hatNumber <= 100) {
        System.out.println("Hats = " + hatNumber);
    } else {
        hatNumber = 0;
    }
    photoNumber = in.readInt("How many photographs would you like?: \n");
    if (photoNumber > 0 && photoNumber <= 100) {
        System.out.println("Photographs = " + photoNumber);
    } else {
        photoNumber = 0;
        jarNumber = in.readInt("How many Jars of maple syrup?: \n");
        if (jarNumber > 0 && jarNumber <= 100) {
            System.out.println("Jars = " + jarNumber);
        } else {
            jarNumber = 0;
        }
    }
    System.out.println("Hats = " + hatNumber);
    System.out.println("Photographs = " + photoNumber);
    System.out.println("Jars = " + jarNumber);

答案 1 :(得分:0)

 if (hatNumber <= 0 && hatNumber > 100) 

在任何情况下,此条件都不可能成立。您应使用以下条件

 if (hatNumber > 0 && hatNumber < 100) {
    System.out.println("Hats = " + hatNumber);
 }

答案 2 :(得分:0)

您在

之后的行中缺少右括号
photoNumber = 0;