2016-03-26 70 views
-1

什麼我工作在一個文件中讀取並將它傳遞給我已經有這個做一個ArrayList:如何將ArrayList方法傳遞給同一類中的其他方法?

public ArrayList readInPhrase() { 

    String fileName = "wholephrase.txt"; 
    ArrayList<String> wholePhrase = new ArrayList<String>(); 

    try { 

     //creates fileReader object 
     FileReader inputFile = new FileReader(fileName); 

     //create an instance of BufferedReader 
     BufferedReader bufferReader = new BufferedReader(inputFile); 

     //variable to hold lines in the file 
     String line; 

     //read file line by line and add to the wholePhrase array 
     while ((line = bufferReader.readLine()) != null) { 
      wholePhrase.add(line); 
     }//end of while 

     //close buffer reader 
     bufferReader.close(); 

    }//end of try 

    catch(FileNotFoundException ex) { 
     JOptionPane.showMessageDialog(null, "Unable to open file '" + 
       fileName + " ' ", "Error", 
       JOptionPane.INFORMATION_MESSAGE, null); 
    }//end of file not found catch 

    catch(Exception ex) { 
     JOptionPane.showMessageDialog(null, "Error while reading in file '" 
       + fileName + " ' ", "Error", 
       JOptionPane.INFORMATION_MESSAGE, null); 
    }//end of read in error 

    return wholePhrase; 

}//end of readInPhrase 

,我現在遇到的問題是,我想經過此ArrayList和從它隨機選擇一個短語最終將星號的 附加到所選短語的一部分。我嘗試了各種不同的方式來做到這一點。

這是我試圖在最後一次嘗試:據我所看到

public String getPhrase(ArrayList<String> wholePhrase) { 

    Random random = new Random(); 

    //get random phrase 
    int index = random.nextInt(wholePhrase.size()); 
    String phrase = wholePhrase.get(index); 

    return phrase; 

    }//end of getPhrase 
+4

你實際上沒有解釋發生了什麼問題。 – elhefe

+1

*「我不完全確定我在哪裏迷路」*同上。我們也失敗了,因爲不清楚你試圖做什麼不同於你已經做的。我的意思是,它不能像*「追加星號的」*部分一樣簡單,因爲字符串連接很容易。 – Andreas

+2

爲什麼你要在返回值中加上括號? 'return'後沒有空格。使它看起來像一個方法調用。 'return wholePhrase;'和'return phrase;'是你應​​該怎麼做的。 – Andreas

回答

1

從對問題的意見,你說你叫getPhrase這樣的:

HangmanPhrase.getPhrase() 

...這導致錯誤

method getPhrase in class HangmanPhrase cannot be applied to given types; 
required: ArrayList<String> found: no arguments reason: 
    actual and formal argument lists differ in length 

這樣做的原因是,getPhrase需要一個ArrayList<String>作爲參數:

public String getPhrase(ArrayList<String> wholePhrase) { 

你需要一個ArrayList傳遞給方法getPhrase像這樣:

ArrayList<String> myListOfStrings = new ArrayList<String>(); 
// do stuff with myListOfStrings 
getPhrase(myListOfStrings); 

而且,由於getPhrase是一個實例方法,而不是一個靜態方法,你不能把它通過HangmanPhrase.getPhrase。您需要創建一個HangmanPhrase的實例並從該實例調用該方法。

+0

謝謝你的解釋。現在對我來說更有意義。我現在應該能夠解決這個問題 – CamronT

0

兩個問題。

  1. Java中的返回語句遵循'返回變量名';'而不是方法類型的調用。
  2. 由於索引從零開始,因此您應該使用隨機數減1來獲取數組列表。
+3

至於#2,'nextInt(int)'返回從零開始的數字。 – Andreas

0

然後只是做getPhrase(readInPhrase())。編譯器將調用getPhrase(),然後在堆棧跟蹤返回點位於getPhrase(...)處對readInPhrase()進行蒸發。這將返回ArrayList(順便說一句,需要用<String>進行類型參數化)。然後,以ArrayList作爲參數調用getPhrase(),然後獲得該短語,然後有很多歡樂。

此外,readInPhrase()必須返回一個ArrayList<String>(在Java中1.5+)

相關問題