This method must return a result of type boolean(Java)

前端 未结 3 1761
一整个雨季
一整个雨季 2021-01-26 12:14

this is my code.

boolean checkHit2() {
    if (cx < 0 || cx >= 640) {return true;}
    if (cy < ground[(int)cx]) {return false;}
    if (cx < blue +         


        
相关标签:
3条回答
  • 2021-01-26 12:33

    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

    0 讨论(0)
  • 2021-01-26 12:39

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

    0 讨论(0)
  • 2021-01-26 12:44

    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.

    0 讨论(0)
提交回复
热议问题