生成唯一的随机数字JAVA
问题描述:
我试图从字符串问题中获取混洗字符。但是角色重复。生成唯一的随机数字JAVA
随机方法
public ArrayList<Integer> Random(int length) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=0; i<length; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
return list;
}
MainActivity
strQuestion = c.getString("question");
int length = strQuestion.length();
str_buff.getChars(0, length, char_text, 0);
for(int i=0;i<length;i++){
int k = Random(length).get(i);
TextView tv = new TextView(this);
tv.setText(String.valueOf(char_text[k]));
tv.setId(k);
tv.setTextSize(30);
tv.setBackgroundColor(0xff00ff00);
tv.setPadding(5, 5, 5, 5);
tv.setOnTouchListener(new MyTouchListener());
layout.addView(tv);
}
答
如果我正确理解你在问什么,你想为字符串“question”中的每个字母创建一个新的TextView,但是你希望它们是以随机顺序创建的?
您现在写的内容会为MainActivity中的for循环的每次迭代创建一个新的“随机”ArrayList
。我想你想要将你的调用移动到for循环之外的Random(length)。将在MainActivity循环应该是这个样子......
ArrayList<Integer> randomized = Random(length);
for(int i=0;i<length;i++){
int k = randomized.get(i);
TextView tv = new TextView(this);
tv.setText(String.valueOf(char_text[k]));
tv.setId(k);
tv.setTextSize(30);
tv.setBackgroundColor(0xff00ff00);
tv.setPadding(5, 5, 5, 5);
tv.setOnTouchListener(new MyTouchListener());
layout.addView(tv);
}
注意:如果分配给strQuestion字符串中已经重复的字母,你会需要的,如果修改方法(如“香蕉”)。您只需要在TextView中输出唯一的字母。
+0
非常感谢。有用。 – user3651158 2015-03-03 03:15:49
答
您正在使用的for循环的每个迭代不同的洗牌。给定元素通常会出现在不同洗牌的不同位置,因此您可以多次查看它。
改为在循环外创建一个混洗列表。
作为一个数组列表将字符串转换为字符串并将其转换回字符串是否更有意义... – Shashank 2015-03-02 18:15:21