gpt4 book ai didi

java - 如何正确嵌套此 If 语句

转载 作者:行者123 更新时间:2023-12-02 08:59:23 32 4
gpt4 key购买 nike

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

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);

关于java - 如何正确嵌套此 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60274822/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com