Layne Reiners
Layne Reiners

Reputation: 1

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.

Upvotes: 0

Views: 1593

Answers (3)

Akash Thakare
Akash Thakare

Reputation: 23012

"This method must return a result of type boolean"

Means your method should return the boolean value for every case. Currently it will return boolean if one of your if condition is true. What about if none of your if condition is 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. You should add return false at the end of the method.

Upvotes: 2

UnknownOctopus
UnknownOctopus

Reputation: 2297

In your method you must return a variable in each case (for each if statement), in this case, a boolean.

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. 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.

To see more about return, click here

Upvotes: 1

Kenny Tai Huynh
Kenny Tai Huynh

Reputation: 1599

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. Please ignore the first comment.

Upvotes: -1

Related Questions