java替换所有相同字符,java替换重复的字符

So for an assignment I have to generate a random code, and have someone guess the code in the console. Now My problem is that I can't seem to find a way to replace any duplicate characters in the code. The code must range in "ABCDEF", and contain 4 letters. This is what I got so far:

char codeLetters;

String masterCode;

StringBuilder strings = new StringBuilder();

Random random = new Random();

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

codeLetters = code[random.nextInt(code.length)];

strings.append(codeLetters);

}

masterCode = strings.toString();

String temp = "";

boolean isDuplicate = false;

for (int i = 0; i < masterCode.length(); i++) {

isDuplicate = false;

char comparisonChar = masterCode.charAt(i);

for (int j = i + 1; j < masterCode.length(); j++) {

char nextChar = masterCode.charAt(j);

if (comparisonChar == nextChar) isDuplicate = true;

}

if (!isDuplicate) temp = temp + comparisonChar;

}

masterCode = temp;

System.out.println(masterCode);

it prints either a code consisting out of 2-3 letters, or a code containing 5 or 6 letters, and rarely a correct code with 4 letters. What this code does as far as I know is not add the duplicate characters, but I want it to Replace them instead with another character. Is there someway to replace the characters with another randomly generated char, which is not in the String yet, without using Sets?

解决方案

It sounds like you only want to use each letter in code once? Why don't you set that up from the beginning using an ArrayList, and removing each character if it is randomly selected:

// copy `code` into a temporary arraylist

ArrayList possibleLetters = new ArrayList(code.length);

for (char c : code) possibleLetters.add(c);

// select randomly "without replacement"

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

int index = random.nextInt(possibleLetters.size());

codeLetters = possibleLetters.remove(index);

strings.append(codeLetters);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值