2013-12-07 105 views
2

在我的代碼中搜索方法中搜索字符串時,我總是收到此錯誤。我已經通過很多例子來解決這個問題,但是我找不到任何例子。謝謝你的幫助,並建議你可以給。類型不匹配無法從元素類型對象轉換爲字符串

public class runNote { 

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    Notebook note = new Notebook(); 
    note.storeNote("happy"); 
    note.storeNote("hello there"); 
    note.storeNote("work at 5"); 
    note.storeNote("BBQ Time"); 
    note.storeNote("UNI!!!!"); 
    note.storeNote("Dont miss lecture at 9:15"); 
    System.out.println(note.numberOfNotes()); 
    note.showNote(1); 
    note.searchNotes("hap"); 

}} 




public class Notebook{ 


/** 
* Perform any initialization that is required for the 
* notebook. 
*/ 
public Notebook() 
{ 
    notes = new ArrayList(); 
} 

/** 
* Store a new note into the notebook. 
* @param note The note to be stored. 
*/ 
public void storeNote(String note) 
{ 
    notes.add(note); 
} 

/** 
* @return The number of notes currently in the notebook. 
*/ 
public int numberOfNotes() 
{ 
    return notes.size(); 
} 

/** 
* A simple search engine to find the correct notes. 
*/ 
public void searchNotes(String search){ 
    for (String item : notes){ 
     if (item.contains(search)){ 
     System.out.println(item); 
     } 
    } 
} 

/** 
* Show a note. 
* @param noteNumber The number of the note to be shown. 
*/ 
public void showNote(int noteNumber) 
{ 
    if(noteNumber < 0) { 
     // This is not a valid note number, so do nothing. 
    } 
    else if(noteNumber < numberOfNotes()) { 
     // This is a valid note number, so we can print it. 
     System.out.println(notes.get(noteNumber)); 
    } 
    else { 
     // This is not a valid note number, so do nothing. 
    } 
} 
} 
+0

什麼是錯誤? – hrv

+1

粘貼確切完整的錯誤消息,並告訴我們它指向的是哪一行。 –

+2

「筆記」聲明在哪裏?當你聲明它爲'ArrayList '時,你是否聲明它爲'ArrayList'? –

回答

4

爲全局變量備註添加到您的類

public class Notebook{ 
ArrayList<String> notes = null; 

.... 
} 

在構造函數中,這樣做:

public Notebook() 
{ 
    notes = new ArrayList<String>(); 
} 
+2

這是*成員變量,而不是全局*變量。 –

+0

這是一個默認的構造函數 – openmike

+0

@Sage或完全不同的編譯器錯誤 –

5

你在這行有例外:

for (String item : notes) 

notes是一個ArrayList聲明爲原始類型,雖然我沒有看到聲明,我可以看到這行初始化:

notes = new ArrayList(); 

Object您需要聲明notes它認爲它的元素類型的ArrayList<String>類型如:

ArrayList<String> notes = new ArrayList<>(); 
+0

如果我更改聲明,我得到此錯誤:線程「主」java.lang.NullPointerException異常 \t at lab8.Notebook.storeNote(Notebook.java:32) \t at lab8.runNote.main(runNote。 java:8) – user202051

+0

你是否像上面描述的那樣初始化了'notes'列表? – Sage

0

試試這個:notes = new ArrayList<String>();

0

你不聲明變量

0音符
相關問題