[英]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").
我可以以某种方式做出正确的模式,但是问题是我只能在控制台上显示它们,而找不到找到将它们另存为String的方法(例如“ 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
:
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 然后在您的for循环中执行
answer+=words[list.get(i)];
When you leave the for loop 当您离开for循环时
System.out.println(answer);
Will have what you want. 将拥有您想要的。 To do it more efficiently I'd read up on StringBuilder.
为了更有效地做到这一点,我将阅读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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.