首页 > 解决方案 > Golf return output logic issue

问题描述

Hey guys so I am trying to do a HW question for a java class and I am having some trouble understanding the logic. This is the question they asked of me:

Golf scores record the number of strokes used to get the ball in the hole. The expected number of strokes varies from hole to hole and is called par (i.e. 3, 4 or 5). Each score has a cute name based on the actual strokes taken compared to par. Return "Eagle" if strokes is two less than par. Return "Birdie" if strokes is one less than par. Return "Par" if par matches strokes exactly. Return "Bogey" if strokes is one more than par. Return "Error" if par is not 3, 4 or 5.

This is my code:

public class Main {
   
   public String golfScore(int par, int strokes){
      
      if(strokes <= par - 2){
         return "Eagle";
      }
      else if(strokes <= par -1){
         return "Birdie";
      }
      else if(strokes == par){
         return "Par";
      }
      else if(strokes > par + 1){
         return "Bogey";
      }
      else{
         return "Error";
      }
   }
   
   // this method not used but needed for testing
   public static void main(String[] args) {
   }
}

When I run the results I get correct for everything except for the last test.

But this logic doesn't make sense to me cause it should be invalidating my if statement. Cause 1 > 2 + 1 is false therefore it should be outputting an error. Why is my program outputting bogey?

标签: javalogic

解决方案


解决了!感谢克里斯福伦斯!

if ((par != 3) && (par != 4) && (par != 5)){
     return "Error";
  }
  else if(strokes <= par - 2){
     return "Eagle";
  }
  else if(strokes <= par -1){
     return "Birdie";
  }
  else if(strokes == par){
     return "Par";
  }
  else{
     return "Bogey";
  } 

}


推荐阅读