Zachary Sweeney Zachary Sweeney - 1 year ago 77
Java Question

How do I compare a parameter to elements in an array that are next to it?

I am doing a worksheet for my AP Computer science class and I have run into this question.

"Write the complete definition for the isABeat method. The method accepts an integer parameter and returns whether or not it's a beat: a beat is defined as a value that is greater than its immediate neighbors. You can assume the first and last values do not represent beats."

With this example of an array:

[4, 5, 7, 10, 9, 5, 0, -2, -8, -10, -10, -7]

  • isABeat(3) returns true,

  • isABeat(9) returns false.

Here s the starting code my teacher gave me for the worksheet:

public class EKG {
private int[] beats = new int[6000]; // holds data for each bet every tenth of a second for ten minutes
//constructors, accessors, mutators and toString present but not shown
public void correctBeatData() {}
public boolean isABeat(int spot) {}
public in countBeats() {}
public int averageBPM() {}
public int findNextBeat(int where) {}
public boolean hasArrhythmia() {}

Answer Source

Here is your solution with documentation:

public boolean isABeat(int spot) //index would have been a better name just saying.
       //used this to avoid ArrayOutOfBounds Further down as it will just break when it returns false
      if(spot>=beats.length-1||spot<=0) // spot is out of bounds therefore it is false
           return false;
       //Makes sure it is greater than both neighbors.
       if(beats[spot]>beats[spot-1] && beats[spot] >beats[spot+1])
       return true;
       return false; //if its false



It tests if spot is out of bounds.. If it is, that means it definitely cannot be a beat. Thus, we break the call by returning false(Avoiding out of bounds in the conditional below that). Next, we check if its neighbors are both less than the value at the spot. If the conditional is satisfied, it will return true. Otherwise, it will return false. Hopefully the addition of the logic and the code help you understand how to go about with the solution