Reputation: 33
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)]);
}
Upvotes: 2
Views: 43
Reputation: 3755
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);
Upvotes: 1
Reputation: 151
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.
Upvotes: 1
Reputation: 311528
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();
Upvotes: 2