2013-05-03 62 views
0

我如何隨機化數組字中的每個字符串...「位置」到「Psioiont」。基本上我需要做的是我要顯示我在那裏一個人去思考,纔可以回答一個有趣的方式...爭奪字符串

你好--->「hlelo」

public class Rnd { 
    public static void main(String[] args) { 

     List list = new ArrayList(); 
     Collections.shuffle(list); 

     String[] words =new String[]{"Position", "beast", "Hello"}; 
     Collections.shuffle(Arrays.asList(words)); 
    } 
} 
+2

duplicatef http://stackoverflow.com/q/3316674/866172 – Jalayn 2013-05-03 16:08:46

+0

你當前只是在列表中洗牌單詞的順序,而不是字符串中字符的順序。 – berry120 2013-05-03 16:13:08

回答

0

的轉換每個字符串添加到一個字符數組中,然後調用shuffle,然後再次創建一個字符串。

當然,這實際上並不適用於真正的Unicode - 如果可能存在非BMP字符或複合字符,沒有簡單的方法來實現它。但它可能會爲這種似乎是小遊戲。

+0

剛試過這個。奇怪的是,它不工作.. – christopher 2013-05-03 16:11:18

0

只要把字符每個字符串到一個列表中,然後調用Collections.shuffle(),然後把它們放回一個字符串:

String x = "hello"; 
    List<Character> list = new ArrayList<Character>(); 
    for(char c : x.toCharArray()) { 
     list.add(c); 
    } 
    Collections.shuffle(list); 
    StringBuilder builder = new StringBuilder(); 
    for(char c : list) { 
     builder.append(c); 
    } 
    String shuffled = builder.toString(); 

    System.out.println(shuffled); //e.g. llheo