簡體   English   中英

如何將參數與其旁邊的數組中的元素進行比較?

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

我正在為我的 AP 計算機科學課做一個工作表,我遇到了這個問題。

“為 isABeat 方法編寫完整的定義。該方法接受一個整數參數並返回它是否為節拍:節拍定義為大於其直接鄰居的值。您可以假設第一個和最后一個值不是代表節拍。”

使用這個數組示例:

[4, 5, 7, 10, 9, 5, 0, -2, -8, -10, -10, -7]
  • isABeat(3) 返回真,
  • isABeat(9) 返回 false。

這是我的老師給我的工作表的起始代碼:

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() {}

我想,在給定方法: 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];
}

這是您的文檔解決方案:

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

}

邏輯:

它測試點是否出界。如果是,那意味着它絕對不能是一個節拍。 因此,我們通過返回 false 來中斷調用(避免在下面的條件中越界)。 接下來,我們檢查它的鄰居是否都小於現場的值。 如果條件滿足,則返回true。 否則,它將返回false。 希望添加的邏輯和代碼可以幫助您了解如何使用解決方案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM