2015-03-02 222 views
0

我試圖從字符串問題中獲取混洗字符。但是角色重複。生成唯一的隨機數字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); 
     } 
+0

作爲一個數組列表將字符串轉換爲字符串並將其轉換回字符串是否更有意義... – Shashank 2015-03-02 18:15:21

回答

0

如果我正確理解你在問什麼,你想爲字符串「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

4

您正在使用的for循環的每個迭代不同的洗牌。給定元素通常會出現在不同洗牌的不同位置,因此您可以多次查看它。

改爲在循環外創建一個混洗列表。