Axelgria
Axelgria

Reputation: 15

adding a String from a String Array into an ArrayList

String [] words = { "apple", "orange", };
String Word = words[wordGenerator];            //wordsGenerator is just a rand(); which return a integer.

String [] letters;
List<String> wordList;

letters = new String[12];
wordList = new ArrayList<String>(Arrays.asList(letters));

letters = Word.split("(?!^)");

By doing the above code I know that I'll get a Array called 'letters' with the first 5 memory as a, p, p, l, e if it generate apple am I right?

If so, how can I pass this 5 strings from the 'letters' array into the wordList? The solution seems somehow easy but I just couldn't come out with it. Any help would be greatly appreciated. Thank you.

Upvotes: 1

Views: 1336

Answers (2)

Ashraf Sayied-Ahmad
Ashraf Sayied-Ahmad

Reputation: 1763

Here a snippet code:

/**
 * @param args
 */
public static void main(String[] args) {
    //init the wordList
    List<String> wordList=new ArrayList<String>();
    //init the word buffer
    String [] letters = new String[12];
    //init the data
    String [] words = { "apple", "orange", };
    //pick a random number
    int wordsGenerator = new Random().nextInt(words.length);
    //pick a random word
    String Word = words[wordsGenerator];            
    //process the word...
    letters = Word.split("(?!^)");
    //add the word to the wordList
    String mergedWord = join(letters);
    wordList.add(mergedWord);

}

/*
 * Merges a set of strings to one string
 */
static String join(String[] strs){
    StringBuffer sb=new StringBuffer();
    for (String item : strs) {
        sb.append(item);
    }
    return sb.toString();
}

}

Upvotes: 0

5hssba
5hssba

Reputation: 8079

 for(int i=0;i<letters.length();i++{
 wordlist.add(letters[i]);
 }

I think.. this is what you were asking...?

Upvotes: 1

Related Questions