将 if 语句放在应该 return 一个 int 值的方法中
Putting if statement inside a method that is supposed to return an int value
我在通过一个方法中的 if 语句实现我的条件时遇到了问题,该方法最后应该是 return 一个 int 值。有人提醒我,您不能在应该 return int 值的方法中包含布尔值。以下是上下文代码:
public int getDayOfWeek (int year, int month, int day) {
int i1 = 4;
int i2= 2;
int i3= 0;
int i4 = 6;
if (year => 17 && year =< 18) {
centuryNum = i1;
return centuryNum;
}
....
}
在这种方法中实现一系列 if 语句的正确方法是什么?
您总是需要在此方法中 return 一个 int 值。在您的情况下,我们可以看到的唯一 return 语句位于 if 条件中,该条件可能不会计算为真。
此外,if 语句本身的语法不正确,这也可能是您的问题。 greater/smaller 比符号应该排在第一位。有关如何使用这些运算符的信息,请参阅 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html。请注意,阅读编译器错误也可能对您有所帮助。
Equality and Relational Operators
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
year >= 17 && year <= 18
是正确的。您将收到 year => 17 && year =< 18
的编译器错误。
见 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
学习基本操作。
Greater than or equal to: >=
Less than or equal to: <=
我在通过一个方法中的 if 语句实现我的条件时遇到了问题,该方法最后应该是 return 一个 int 值。有人提醒我,您不能在应该 return int 值的方法中包含布尔值。以下是上下文代码:
public int getDayOfWeek (int year, int month, int day) {
int i1 = 4;
int i2= 2;
int i3= 0;
int i4 = 6;
if (year => 17 && year =< 18) {
centuryNum = i1;
return centuryNum;
}
....
}
在这种方法中实现一系列 if 语句的正确方法是什么?
您总是需要在此方法中 return 一个 int 值。在您的情况下,我们可以看到的唯一 return 语句位于 if 条件中,该条件可能不会计算为真。
此外,if 语句本身的语法不正确,这也可能是您的问题。 greater/smaller 比符号应该排在第一位。有关如何使用这些运算符的信息,请参阅 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html。请注意,阅读编译器错误也可能对您有所帮助。
Equality and Relational Operators
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
year >= 17 && year <= 18
是正确的。您将收到 year => 17 && year =< 18
的编译器错误。
见 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
学习基本操作。
Greater than or equal to: >=
Less than or equal to: <=