[英]This method must return a result of type boolean(Java)
this is my code. 这是我的代码。
boolean checkHit2() {
if (cx < 0 || cx >= 640) {return true;}
if (cy < ground[(int)cx]) {return false;}
if (cx < blue + 15 && cx > blue - 15) {
score = (int)score + 1;
What am I doing wrong? 我究竟做错了什么? it gives me the error message "This method must return a result of type boolean".
它给我错误信息“此方法必须返回布尔类型的结果”。 Please help.
请帮忙。
"This method must return a result of type boolean"
“此方法必须返回布尔类型的结果”
Means your method should return the boolean
value for every case . 意味着您的方法应为每种情况返回
boolean
值。 Currently it will return boolean
if one of your if condition is true
. 当前,如果条件之一为
true
,它将返回boolean
。 What about if none of your if condition is true
? 如果您的if条件都不
true
怎么办? In this case compiler will not be able to return anything to the caller of the method. 在这种情况下,编译器将无法向该方法的调用者返回任何内容。 So that compiler is telling you to add a
return
statement for method for every case no matter condition satisfy or not. 这样,无论条件是否满足,编译器都会告诉您为每种情况添加方法的
return
语句。 You should add return false
at the end of the method. 您应该在方法末尾添加
return false
。
In your method you must return
a variable in each case (for each if
statement), in this case, a boolean. 在您的方法中,您必须在每种情况下(对于每个
if
语句)都return
一个变量,在这种情况下为布尔值。
Example: 例:
boolean checkHit2() {
if (cx < 0 || cx >= 640) {return true;}
if (cy < ground[(int)cx]) {return false;}
if (cx < blue + 15 && cx > blue - 15){
score = (int)score + 1;
return false;
}
Also, just to clean up your code a bit, the curly brackets are unneeded if the contents of the block is only one line. 另外,只是为了稍微整理一下代码,如果块的内容只有一行,则不需要大括号。 For example you can use:
例如,您可以使用:
boolean checkHit2() {
if (cx < 0 || cx >= 640) return true;
if (cy < ground[(int)cx]) return false;
if (cx < blue + 15 && cx > blue - 15){
score = (int)score + 1;
return false;
}
Functionally, they act the same. 在功能上,它们的行为相同。 It's just a useful shortcut to clean up your code :).
这只是清理代码的有用捷径:)。
In this example i simply returned false because i'm insure of the functionality of your program or how you would like it to work. 在此示例中,我只是返回false,因为我可以确保您的程序的功能或您希望它如何工作。 You could return a value based on a
if
or else
statement, etc. but it's up to you and what you want your program to do. 您可以基于
if
或else
语句等返回一个值,但这取决于您以及您希望程序执行的操作。
To see more about return
, click here 要查看有关
return
更多信息, 请单击此处
This line: 这行:
<b>if (cx < blue + 15 && cx > blue - 15){ </b>
Should be changed to 应该改为
<b>if((cx < (blue + 15)) && (cx > (blue -15))){</b>
but I think you should move the comparation out like: 但我认为您应该像这样删除比较:
int bluePlus = blue + 15;
int blueMinus = blue - 15;
if(cx < bluePlus && cx > blueMinus){
EDIT: The error means that you miss to return boolean after all. 编辑:错误意味着您毕竟错过了返回布尔值。 After the if
如果之后
if(cx < bluePlus && cx > blueMinus){
then you need to add return to the result. 那么您需要在结果中添加return。 Please ignore the first comment.
请忽略第一条评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.