Java:生成唯一的随机字符

问题描述 投票:1回答:2

我有一串“随机”字符。我根据字符串中的位置为每个字符分配了一个数值,然后设置一个循环以在任何随机位置选择时输出字符。到目前为止,这是我的代码:

public class Random9_4 {

  public static void main(String[] args) {

    final String chords = "ADE";
    final int N = chords.length();
    java.util.Random rand = new java.util.Random();
    for(int i = 0; i < 50; i++)
    {
        //char s = chords.charAt(rand.nextInt(N));
        //char t = chords.charAt(rand.nextInt(N));

        System.out.println(chords.charAt(rand.nextInt(N)));
        //temp variable
        //while(s == t)
        //{
        //  
        //}System.out.println(chords.charAt(rand.nextInt(N)));
    }
  }
}

截至目前它的工作正常,但角色有时会重复。我想要它,这是字符的“唯一”输出(意味着后续字符不重复)。我知道一种方法是使用临时变量来检查前一个字符和下一个将显示的字符,但我不确定如何开始。

java random character
2个回答
1
投票

如果新字符与上一次迭代中生成的字符匹配,则需要使用内部循环生成新字符。

temp是一个临时字符变量,它记住生成的最后一个字符。所以在while循环中,我们将迭代直到生成一个新字符,该字符与temp变量中的字符不同。

如果生成了一个新字符,它将被分配给temp变量,因此在下一次迭代中可以应用相同的逻辑。

public static void main(String[] args) {
        final String chords = "ADE";
        final int N = chords.length();
        Random rand = new Random();
        char temp = 0;
        for (int i = 0; i < 50; i++) {
           char s = chords.charAt(rand.nextInt(N));
           while(s == temp){ //loop until a new character is generated, this loop will stop when s != temp
               s = chords.charAt(rand.nextInt(N));
           }
           temp = s; //assign current character to the temp variable, so on next iteration this can be compared with the new character generated.
           System.out.println(s);
        }
}

0
投票

我不确定我是否理解你的问题。

它只是创建一个变量来存储以前的输出吗?像下面的代码。

    final String chords = "ADE";
    final int N = chords.length();
    Random rand = new Random();
    Character curr = null;
    Character prev = null;
    for (int i = 0; i < 50; i++) {
        curr = chords.charAt(rand.nextInt(N));
        while (curr == prev)
            curr = chords.charAt(rand.nextInt(N));

        prev = curr;
        System.out.println(curr);
    }
© www.soinside.com 2019 - 2024. All rights reserved.