从随机数组中创建一个字符串变量

时间:2014-07-28 08:44:49

标签: java arrays string random

import java.util.Random;

public class DotComTestDrive {

    public static void main(String [] args) {

        String stringOfWords[] = {"Do", "You", "Like", "Me"};
        boolean correctOrder = true;
        int numberOfResets = 0;
        String correctString;
        String realString[];

        while (correctOrder == true) {

            System.out.println();

            for (int x = 0 ; x < 4 ; x++) {

                int rand = (int) (Math.random() * 4);

                System.out.print(stringOfWords[rand]);
                System.out.print(" ");

                numberOfResets++;
            }
            // Place If statement here to change correctOrder to false when the new string is "Do You Like Me "

        }

        System.out.println(numberOfResets);
    }
}

我的主要目标是尝试获得新的随机四个单词 它会输出到String[],然后我可以使用If语句来 查看字符串是否与原始字符串匹配。然后我会制作boolean “correctOrder”为false,结束循环。

我知道如果这不是一个很好或明确的问题,那就很简单也很抱歉。 只是想学习基础知识和任何事情都有帮助,谢谢!

2 个答案:

答案 0 :(得分:0)

我建议使用列表并在每次循环时随机播放。

Map<K,V> map = xxxx;
List<Map.Entry<K,V>> list = new ArrayList<Map.Entry<K,V>>(map.entrySet());

// each time you want a different order.
Collections.shuffle(list);

for(Map.Entry<K, V> entry: list) { /* ... */ }

答案 1 :(得分:0)

假设您要将这些String放在realString中,您应该执行以下操作/

  • 初始化此Array
  • for循环中指定其中一个元素。

例如:

String realString[] = new String[4];

while(correctOrder == true){
    for(int x = 0; x < 4; x++){ 
        int rand = (int) (Math.random()*4);
        System.out.print(stringOfWords[rand]);
        System.out.print(" ");

        realString[x] = stringOfWords[rand];
    }
}

另外,既然我就是这样,我建议你改变代码中的一些内容:

  • 无需指定== trueboolean变量可以自行测试。
  • 通常首选使用Random类(而不是Math类)。您可以拥有final Random r = new Random(),只需使用int
  • 即可在[0, 4[范围内获得随机r.nextInt(4)