Search code examples
javaarraysbluej

Adding a list of strings to an array - new Java user


I have this following code;

import java.util.ArrayList;

public class Sequence
{
    // the numbers in the sequence

    private ArrayList<String> list;
    //defining an array called list
    String dwade;

    public Sequence(String s)
    {
        dwade = s;
    }

    public ArrayList<String> conversion()
    {
        for (String retval: dwade.split(",")) {
            list.add(retval)
        }
        return list;           
    }
}

What i'm trying to do in the method for conversion is to split the string s and place the split strings into an array.

e.g. s = "1,5,7,0"
dwade = "1,5,7,0"
list= ["1", "5", 7", "0"]   <--this is an array/matrix

But when i compile this in bluej, i get an error. Whats an easy way to do this (for beginers)

Help is much appreciated!


Solution

  • Try this:

    public ArrayList<String> conversion() {
        List<String> list = new ArrayList<String>();
        for (String retval : dwade.split(",")){
            list.add(retval);
        }
        return list;
    }