2010-09-20 18 views
5

我需要幫助。對於這個特定的方法。我試圖讓它返回一個我標記爲的數組列表。如何從方法返回陣列列表

public ArrayList read(){ 

    BufferedReader inputStream = null; 
    try { 
    inputStream = new BufferedReader(new FileReader("processes1.txt")); 
    String l; 
    while ((l = inputStream.readLine()) != null) { 

     ArrayList<String> tokens = new ArrayList<String>(); 

     Scanner tokenize = new Scanner(l); 
     while (tokenize.hasNext()) { 
     tokens.add(tokenize.next()); 
     } 
     return tokens; 
    } 
    } catch(IOException ioe){ 
    ArrayList<String> nothing = new ArrayList<String>(); 
    nothing.add("error1"); 
    System.out.println("error"); 
    //return nothing; 
    } 
    return tokens; 
} 

我在做什麼錯了?

+1

正如一個評論,它被認爲是很好的做法,一般返回一個列表,而不是一個ArrayList,如果你需要改變在某些時候執行。 – DJClayworth 2011-01-11 16:03:25

回答

10

最後你在做return tokens,但該變量被定義在try塊內部,所以它不能在其外部訪問。您應該添加:

ArrayList<String> tokens = new ArrayList<String>();

你方法的頂部,剛下BufferedReader中。

+0

線程「main」中的異常java.lang.NoSuchMethodError:main 按任意鍵繼續。 。 。 – Luron 2010-09-20 00:58:51

+0

@Luron - 這是一個完全不同的問題,這意味着你沒有在你的類中指定一個'public static void main(String [] args)'方法。這是JVM所要求的 – 2010-09-20 01:33:30

0

嘗試返回在這種情況下更合適的返回類型的ArrayList。泛型類型與您的示例似乎使用它們的方式並不相關。

0

這可能是你的主要方法的錯誤。你是否實例化類並調用read()方法?

0

試試這個:

public ArrayList read(){ 

      File text = new File("processes1.txt"); 

       ArrayList<String> tokens = new ArrayList<String>(); 

       Scanner tokenize; 
      try { 
       tokenize = new Scanner(text); 
       while (tokenize.hasNext()) { 

         tokens.add(tokenize.next()); 
        } 

       } 

      catch(IOException ioe){ 
       ArrayList<String> nothing = new ArrayList<String>(); 
       nothing.add("error1"); 
       System.out.println("error"); 
       //return nothing; 
       } 
      return tokens; 

    }}