作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在捕获用户输入,但将其限制在 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/
我是一名优秀的程序员,十分优秀!