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

前端 未结 3 1762
一整个雨季
一整个雨季 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

提交回复
热议问题