简体   繁体   中英

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

So i'm taking an input file containing strings like:

birthday54
happy75
nifty43
bob1994

These strings are part of an ArrayList. I want to pass this ArrayList through a method that can take each individual string and print them out individually. So basically, how do i take an ArrayList of strings, separate each individual string, and then print those strings? In my code, my while loop condition is true so i have an infinite loop going here and it's only outputting the first string "birthday54" infinitely. I don't know what condition i should have for the while loop. Or if i should even have a while loop. Here is my code:

    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);

I believe you only need to iterate the ArrayList and use the "Get" method to get each string like:

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

or you can use the for each loop

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

cheers!

Change this:

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

To this:

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

It only ouputs " birthday54 " because you didn't increment your i . You can increment it by putting i++ on the end of your while statement, but you will get an error if you do that after you iterate all of your values in your ArrayList . Look my answer, you can simply use for loop to iterate that ArrayList .

Man that's painful to look at, Try this instead of your while loop:

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

No while loop needed, the array list is a Collections object which is a container class in Java that can be iterated by object as well as by index, so this should pull each string out 1 by 1 until it approaches the end of the array list.

Resource on collections in java .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM