簡體   English   中英

如何傳遞字符串的ArrayList並將每個單獨的數組轉換成它自己的字符串(java)?

[英]How to pass in an ArrayList of strings and convert each separate array into it's own string (java)?

所以我正在輸入包含字符串的輸入文件,例如:

birthday54
happy75
nifty43
bob1994

這些字符串是ArrayList的一部分。 我想通過一種可以傳遞每個字符串並單獨打印出來的方法傳遞此ArrayList。 因此,基本上,我如何獲取字符串的ArrayList,將每個單獨的字符串分開,然后打印這些字符串? 在我的代碼中,我的while循環條件為true,所以這里有一個無限循環,它僅無限地輸出第一個字符串“ birthday54”。 我不知道while循環應該有什么條件。 或者,如果我什至應該有一個while循環。 這是我的代碼:

    public static void convArrListToString(ArrayList<String> strings){
            int i=0;
            while (true){
                 String[] convert = strings.toArray(new String[i]);  
                 System.out.println(convert[i]);
                }  
            }
    public static void main(String [] args) 
{
    Scanner in = new Scanner(new File("myinputcases.txt"));
    ArrayList<String> list = new ArrayList<String>();
    while (in.hasNext())
        list.add(in.next());

    convArrListToString(list);

我相信您只需要迭代ArrayList並使用“ Get”方法來獲取每個字符串,例如:

for(int i = 0 ; i < list.size(); i++){ 
   System.out.println(list.get(i)); 
}

或者您可以為每個循環使用

for(String s : list){ 
 System.out.println(s);
}

干杯!

更改此:

while (true) {
    String[] convert = strings.toArray(new String[i]);  
    System.out.println(convert[i]);
}  

對此:

for (String strTemp : strings) {
    System.out.println(strTemp);
}

它只。OUPUTS“birthday54”因為你沒有增加你的i 您可以通過將i++放在while語句的末尾來增加它的數量,但是如果在迭代ArrayList所有值之后這樣做會出現錯誤。 看我的答案,您可以簡單地使用for循環來迭代ArrayList

看這個人很痛苦,試試看,而不是while循環:

for (String s : strings) { 
     System.out.println(s); 
}

不需要while循環,數組列表是一個Collections對象,它是Java中的容器類,可以按對象以及按索引進行迭代,因此這應該將每個字符串一一拉出,直到到達數組列表的末尾。

java中關於集合的資源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM