user7428413
user7428413

Reputation: 11

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

Upvotes: 0

Views: 901

Answers (3)

bmc
bmc

Reputation: 857

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.

Upvotes: 0

msagala25
msagala25

Reputation: 1806

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.

Upvotes: 0

manuel
manuel

Reputation: 36

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!

Upvotes: 1

Related Questions