2013-01-03 124 views
-1

我有以下問題...我想從輸入中讀取未知數量的字符串。於是,我製作了一個arraylist'words',並添加了輸入中的所有字符串。然後我想將這個數組列表轉換成簡單的字符串數組''字串'(String [])...正如我所做的那樣,我想檢查一切是否正常(如果單詞保存在'字串'中),所以我 試圖打印整個陣列......但它不給我我想要的東西......看起來像我的代碼不起作用。哪裏有問題? 感謝您的幫助將ArrayList轉換爲數組

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 

    List<String> words = new ArrayList<String>(); 

    while(sc.hasNextLine()) { 
     words.add(sc.nextLine()); 
    } 

    String[] wordsarray = new String[words.size()]; 

    for(int i = 0; i < words.size(); i++) { 
     wordsarray[i] = words.get(i); 
    } 

    for(int i = 0; i < words.size(); i++) { 
     System.out.println(wordsarray[i]); 
    } 
} 
+6

這是什麼輸出? – Zyerah

+0

沒有什麼或兩個字符串充其量只是... – user1926550

+0

它是否間歇地返回兩個字符串?或者你做了一個改變,導致它返回兩個字符串? – Zyerah

回答

0

也能正常工作對我來說:

import java.util.*; 

public class a 
{ 
    public static void main (String [] args) throws Exception 
    { 
    Scanner sc = new Scanner(System.in); 

    List<String> words = new ArrayList<String>(); 

    while(words.size() < 3 && sc.hasNextLine()) { 
     String s = sc.nextLine(); 
     System.out.println ("Adding " + s); 
     words.add(s); 
    } 

    String[] wordsarray = words.toArray(new String [] {}); 

    for(int i = 0; i < words.size(); i++) { 
     System.out.println("Printing ..." + wordsarray[i]); 
    } 
    } 
} 

輸出:

java a 
1 
Adding 1 
2 
Adding 2 
3 
Adding 3 
Printing ...1 
Printing ...2 
Printing ...3 
+0

嘗試做它對於未知數量的輸入 – user1926550

+0

在這種情況下,您必須具備某種條件,您不再需要任何輸入。在我的情況下,我只是增加了3個總數。如果傳遞一個空白字符,您可以查看Jack的響應,停止輸入。這樣,您可以根據需要輸入儘可能多的文本值,只需傳遞空白字符(「」)即可完成輸入。讓我知道你是否需要更多幫助。 – AC1

4

有一個預先烹飪方法做你正在嘗試做的:

ArrayList<String> words = new ArrayList<String>(); 
String[] array = words.toArray(new String[words.size()]); 

但你的代碼似乎是正確的,你確定一切都是ArrayList裏面取精?

通過您的評論,我猜這個問題是你不把所有東西放在循環中。此代碼:

while(sc.hasNextLine()) { 
    words.add(sc.nextLine()); 
} 

只能使用一次。如果你繼續插入單詞並按回車鍵,你已經在循環之外了,因爲Scanner已經到了一個沒有更多行要讀取的點。

你應該這樣做:

boolean finished = false; 

while (!finished) { 
    while(sc.hasNextLine()) { 
     String line = sc.nextLine(); 
     if (line.equals("")) 
     finished = true; 
     else 
     words.add(sc.nextLine()); 
    } 
    } 
} 
+0

是的,我打印出特定元素並且它們都OK – user1926550