[英]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.我正在为我的 AP 计算机科学课做一个工作表,我遇到了这个问题。
"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."
“为 isABeat 方法编写完整的定义。该方法接受一个整数参数并返回它是否为节拍:节拍定义为大于其直接邻居的值。您可以假设第一个和最后一个值不是代表节拍。”
With this example of an array:使用这个数组示例:
[4, 5, 7, 10, 9, 5, 0, -2, -8, -10, -10, -7]
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() {}
I suppose, having given method: countBeats
and field: beats
it is enought to write:我想,在给定方法:
countBeats
和 field: beats
,就可以这样写了:
public boolean isABeat(int spot) {
if(spot < 0 || spot >= beats.length) {
throw new IllegalArgumentException("Argument 'spot' is out of bounds.");
}
if(spot == 0 || spot == beats.length - 1) {
return false;
}
return beats[spot] > beats[spot-1] && beats[spot] > beats[spot+1];
}
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;
else
return false; //if its false
}
LOGIC:逻辑:
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).
因此,我们通过返回 false 来中断调用(避免在下面的条件中越界)。 Next, we check if its neighbors are both less than the value at the spot.
接下来,我们检查它的邻居是否都小于现场的值。 If the conditional is satisfied, it will return true.
如果条件满足,则返回true。 Otherwise, it will return false.
否则,它将返回false。 Hopefully the addition of the logic and the code help you understand how to go about with the solution
希望添加的逻辑和代码可以帮助您了解如何使用解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.