正确嵌套此If语句

正确嵌套此If语句

我正在捕获用户输入,但将其限制在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);

最佳答案

首先,如果期望逻辑“用户可以输入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);

10-06 05:46