簡體   English   中英

從數組int的參數返回布爾值的方法

[英]Method to return boolean from parameter of array int

好的,這是我的第一篇文章。 首先,我一直在嘗試自己解決這個問題,但是已經花了幾個小時,我仍然迷失了方向。 我嘗試搜索網絡,但沒有出現足夠具體的信息。 這是項目的要求:

  1. 該類必須包含一個int類型且名為checkNumber的私有實例字段。在聲明該字段的位置,不應進行任何顯式初始化。
  2. 它必須提供一個無參數的構造函數,用於將checkNumber字段的值初始化為23。
  3. 它必須提供一個名為setCheckNumber的公共方法,該方法采用一個int類型的參數,將私有字段的值設置為該參數的值,並且沒有返回值。 5.它必須提供另一個名為firstLastCheck的公共方法,該方法將ArrayList作為其參數並返回一個布爾值。 如果列表中的初始值或最后一個值等於實例字段checkNumber中的值,則該方法返回true;否則,該方法返回true。 否則返回false。 該方法可以假定該參數是包含至少一個元素的列表。 也就是說,它不是空列表,也不是null。

這是我到目前為止的內容:

public class BasicsA {
 //fields
 private int checkNumber;
 //constructor to initialize fields
 public BasicsA() {
     //initialize checkNumber
     checkNumber = 23;
 }
 //method to take input and change checkNumber
public void setCheckNumber(int nextNumber) {
    checkNumber = nextNumber;
}
//method to return boolean value
public boolean firstLastCheck(ArrayList<Integer>) {

        }
}

現在,我嘗試改變各種事情。 就像使用firstLastCheck(nameofArrayVariable) 通常,它需要一個標識符,但是如果我能使它正常工作,它就無法將Array int作為布爾值返回。 這也使我感到困惑,因為沒有指令先創建數組或將其定義為字段。 當數組中還沒有元素時,如何檢查第一個和最后一個數組元素呢? 您可能會認為checkNumber會將新的int傳遞到數組中,但是並沒有這樣做。

對不起,我希望我不要太復雜了。

編輯:

public boolean firstLastCheck(ArrayList<Integer> listInt) {
        if(listInt.get(0) == checkNumber || listInt.get(listInt.size() - 1) == checkNumber) {
        return true;
    } else {
    return false;
    }
}

那么如何使用BlueJ IDE對此進行檢查? 我不明白它想要什么?

該方法應如下所示:

public boolean firstLastCheck(ArrayList<Integer> yourList) {

    return list.get(0) == this.checkNumber || list.get(yourList.size() - 1) == this.checkNumber;


}

然后,如果要檢查它是否有效,可以在main()函數內聲明一個ArrayList,填充它,最后調用firstLastCheck()方法。 就像這樣:

public static void main(String [ ] args){

    ArrayList <int> my_values = new ArrayList<>();

    my_values.add(1);
    my_values.add(2);
    my_values.add(3);
    my_values.add(23); //the last element is equal to checkNumber

    System.out.print("firstLastCheck result: " + firstLastCheck(my_values));

}

除了類型,還需要給ArrayList一個本地名稱。 然后,您需要檢查第一個和最后一個值。 就像是,

public boolean firstLastCheck(ArrayList<Integer> list) {
    return list.get(0) == checkNumber || list.get(list.size() - 1) == checkNumber;
}

暫無
暫無

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

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