我在使用 Java 中的 if
和 else
语句时遇到很多问题。我正在关注this basic tutorial ,但我正在使用 Eclipse,因为带有 TMC 的 NetBeans 不适合我。
我想做的是 8.2 练习 15,询问您的年龄,如果您超过 17 岁,则您已达到法定成年年龄,如果您未满 17 岁,则尚未达到法定成年年龄。
这是我目前编写的程序:
import java.util.Scanner;
public class ifelse {
public static void main (String args[]){
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
int num1 = 100;
int num3 = 17;
int num2 = Integer.parseInt(reader.nextLine());
boolean isGreater = num1 > num3;
boolean isLesser = num1 < num3;
if (isLesser) {
System.out.println("You have not reached the age of majority yet!");
}
if (isGreater) {
System.out.println("You have reached the age of majority!");
} else {
System.out.println("You have not reached the age of majority yet!");
}
}
}
我试图用 boolean 值和不同编号的int
等来搞乱,但我无法让它工作。目前我可以运行该程序,但无论我输入什么,最终都会显示您已达到成年年龄。
我创建了 boolean 值 isLesser
并在 if
语句中使用它,认为这会有所帮助,但它似乎忽略了第一个 if
语句或其他内容。
我查看了类似的问题和可能有我的答案的问题,但没有一个与我有完全相同的问题。
最佳答案
在编写 if 语句之前,尝试考虑所有可能满足的条件。在这种情况下,有 3...
if (num2 < num3)
{
//less than the age of majority
}
else if (num 2 > num3)
{
//greater than the age of majority
}
else if (num2 == num3)
{
//less than the age of majority
}
或者,我们可以让这变得更简单:
if (num2 > num3)
{
// greater than the age of majority
}
else
{
// less than the age of majority
}
关于java - if 和 else 语句存在很多问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41093026/