我的任务是为我正在学习的类(class)创建一个小型 Java 程序,但我在使用以下代码块时遇到了一些问题:
System.out.println("Please enter your first name:");
userName = sc.nextLine();
System.out.println("What year were you born in?");
birthYear = sc.nextInt();
System.out.println("In the 'dd.mm' format, what are the day and month of your birth?");
dayMonth = sc.nextDouble();
//Cast the user input of type double to an int for the day of Birth
dayOfBirth = dayMonth.intValue();
//Cast the double value for month and cast it to an int
dayMonth = dayMonth - dayOfBirth;
dayMonth = dayMonth * 100;
dayMonth = Math.rint(dayMonth);
monthOfBirth = dayMonth.intValue();
if(birthYear == 2013 || birthYear == 2001 || birthYear == 1989 || birthYear == 1977 || birthYear == 1965 || birthYear == 1953 || birthYear == 1941)
{
if(monthOfBirth == 9 || monthOfBirth == 10 || monthOfBirth == 11)
{
System.out.println(userName + " was born during Spring on " + monthOfBirthName + " " + dayOfBirth + " in Snake year " + birthYear);
}
else if(monthOfBirth != 9 || monthOfBirth != 10 || monthOfBirth != 11)
{
System.out.println(userName + " was born on " + monthOfBirthName + " " + dayOfBirth + " in Snake year " + birthYear);
}
}
if(birthYear != 2013 || birthYear != 2001 || birthYear != 1989 || birthYear != 1977 || birthYear != 1965 || birthYear != 1953 || birthYear != 1941)
{
if(monthOfBirth == 9 || monthOfBirth == 10 || monthOfBirth == 11)
{
System.out.println(userName + " was born during Spring on " + monthOfBirthName + " " + dayOfBirth + " " + birthYear);
}
else if(monthOfBirth != 9 || monthOfBirth != 10 || monthOfBirth != 11)
{
System.out.println(userName + " was born on " + monthOfBirthName + " " + dayOfBirth + " " + birthYear);
}
}
但是我的输出结果如下:
Please enter your first name:
Samuel
What year were you born in?
1977
In the 'dd.mm' format, what are the day and month of your birth?
09.09
Samuel was born during Spring on September 9 in Snake year 1977
Samuel was born during Spring on September 9
我显然不希望重复输出,但是我无法看到我的 if 语句中的逻辑在哪里导致它重复。
如有任何帮助,我们将不胜感激。
谢谢大家
~山姆。
最佳答案
与其单独使用 2 个 if
,不如将它们设为 if-else
或 if-else if
。
if(birthYear == 2013 || birthYear == 2001 || birthYear == 1989 || birthYear == 1977 || birthYear == 1965 || birthYear == 1953 || birthYear == 1941){
....
}
else if(birthYear != 2013 || birthYear != 2001 ||...){
....
}
因为,如果你给出一个 if-if
,那么两个 if
语句都会被执行,而如果你给出一个 if-else if
,第二个 else if
只有在第一个 if
语句失败时才会执行。
关于java - if语句逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15809088/