gpt4 book ai didi

java - 打乱字符串时防止重复字母?

转载 作者:行者123 更新时间:2023-12-01 17:11:16 25 4
gpt4 key购买 nike

我正在创建一个程序,它将输出字符串中的字母,但是是乱序的。它有效,但没有办法阻止一封信多次出现。我该怎么办?

我的代码:

import java.util.Random;


public class Final {

public static void main(String[] args) {
Random rand = new Random();
String str = "pumpkinpie";

String[] split = str.split("");
for(int i = 0; i < split.length; i++){
int randomLet = rand.nextInt(split.length);
System.out.print(split[randomLet]);
}

}

}

最佳答案

您可以将 String 中的每个字符添加到 ArrayList 中,并使用 Collections.shuffle() 方法对其进行打乱,该方法也接受 Random 实例:

    //1. initiate the string you want to shuffle
String originalString = "pumkinpie";
//2. initiate a List into which the characters will be added
List<Character> characterList= new ArrayList<Character>();
//3. add each character from the String to the List
for (char character : originalString.toCharArray()) {
characterList.add(character);
};
//4. shuffle using Collections.shuffle
Collections.shuffle(characterList, new Random());
//5. print each character
for (Character character : characterList) {
System.out.println(character);
}

关于java - 打乱字符串时防止重复字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23685721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com