简体   繁体   中英

saving random letters of an array as a String

I wanna write a program in which different letters of a String Array form different words based on random orders. The most important part is that letters should not be duplicate in one word. I could somehow make the correct pattern but the problem is that I can only show them on console and couldn't find a way to save them as a String (like "OMAN"). Here is my code :

int size = 4;
ArrayList<Integer> list = new ArrayList<Integer>(size);
Random rnd = new Random();
while (list.size()<size) {
    int random = rnd.nextInt(size);
    if (!list.contains(random)) {
        list.add(random);
    }
}
String[] words = {"M","O","A","N"};
for(int i=0 ; i<size ; i++){
    System.out.println(words[list.get(i)]);
}

You could accumulate them to a StringBuilder :

StringBuilder sb = new StringBuilder(size);
for(int i = 0 ; i < size ; i++) {
    sb.append(words[list.get(i)]);
}
String result = sb.toString();

First declare a blank string

String answer = "";

Then in your for loop do

answer+=words[list.get(i)];

When you leave the for loop

System.out.println(answer);

Will have what you want. To do it more efficiently I'd read up on StringBuilder.

You can do something like this,

    int size = 4;
    ArrayList<Integer> list = new ArrayList<Integer>(size);
    Random rnd = new Random();
    while (list.size() < size) {
        int random = rnd.nextInt(size);
        if (!list.contains(random)) {
            list.add(random);
        }
    }
    String[] words = {"M", "O", "A", "N"};
    String finalWord = "";
    for (int i = 0; i < size; i++) {
        finalWord += words[list.get(i)];
    }
    System.out.println(finalWord);

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