2017-10-18 151 views
-1
瞭解列表
public class Worksheet { 
    private ArrayList<DataEntry> data; 
    private String title; 

    public Worksheet(String title) { 
     data = new ArrayList<DataEntry>(); 
     this.title = title; 
    } 

    public ArrayList<DataEntry> getData() { 
     return data; 
    } 

    public String getTitle() { 
     return title; 
    } 

    public Double get(int row, int column) { 
     for (DataEntry dataEntry : data) { 
      if ((dataEntry.getColumn() == column) && (dataEntry.getRow() == row)) { 
       return dataEntry.getValue(); 
      } 
     } 
     return null; 
    } 

    public void set(int row, int column, double val) { 
     boolean isNew = true; 
     for (DataEntry dataEntry : data) { 
      if ((dataEntry.getColumn() == column) && (dataEntry.getRow() == row)) { 
       dataEntry.setValue(val); 
       isNew = false; 
      } 
     } 
     if (isNew) { 
      DataEntry newData = new DataEntry(row, column, val); 
      data.add(newData); 
     } 
    } 

    public int indexOf(int row, int column) { 
     int result = -1; 
     for (DataEntry dataEntry : data) { 
      if ((dataEntry.getColumn() == column) && (dataEntry.getRow() == row)) { 


      } 
     } 
     return result; //to be completed 
    } 
} 

我得到這個代碼的做法我了即將到來的考試,我感到非常壞在編碼學習新概念。如果任何人能夠理解代碼並且爲功能indexOf提供正確答案。需要幫助Java中

我明白用戶創建的函數是如何工作的,我只是想不出要在本體中填充什麼。

indexOf的說明應該使用給定的行和列返回列表數據中DataEntry對象的索引,否則返回-1如果沒有找到這樣的DataEntry對象,則返回-1。

+2

你似乎是的印象是SO是某種編碼學校被你問別人教你的東西,在許多解釋下書籍和教程。對不起,這是你的錯誤觀念。我們提供明確,具體的問題。我們不是替代你坐下來做這個學習的一部分。這是**不**免費導師服務。 – GhostCat

+0

@GhostCat:我同意你的看法。儘管如此,我仍然發現即使在最基本的問題中也總是有一些有趣的東西。對於我來說,這類問題的積極挑戰是:如何以最清晰,正確,簡潔和啓發性的方式來解釋這個非常基本的話題,併爲社區增加價值。在這個具體案例中,我認爲有機會這樣做。 –

回答

1

爲了解indexOf方法,您需要了解列表是什麼;它表示按照定義順序的一系列項目。所以你知道列表中的哪些項目以及它們的順序。

例如:您有一個項目「A」,「B」,「C」,在列表中,那麼你就知道該列表中有三個項目,而「一」是第一項,「B」第二,和「c」第三。如果您想知道例如「b」的位置,則需要掃描或遍歷列表並同時計數。當你發現「b」時,你必須停止計數並返回當前計數。這是indexOf的結果。

只是一個方面說明:當你計數你從0開始 - 這意味着如果第一個元素匹配,那麼indexOf的結果爲0,如果第二個元素匹配,則結果爲1。找不到任何通常返回-1的內容。

一種可能的實現這個邏輯可能是你的情況:

public static int indexOf(int row, int column) { 
    int result = -1; 
    for (DataEntry dataEntry : data) { // expression used for iteration, or scanning, or pass through the list 
     result++; // expression used to increment the counter 
     if ((dataEntry.getColumn() == column) && (dataEntry.getRow() == row)) { 
      return result; // returns the count if found 
     } 
    } 
    return -1; // returns -1 meaning: the message 'not found' 
} 
+0

我知道你必須使用一個計數器(例如計數器++),但我不知道如何通過列表中的值 – jack

+0

以'for(DataEntry dataEntry:data){'開頭並且用'}'關閉的表達式是用於通過,即迭代或掃描列表。 –