因此,对于作业,我必须生成随机代码,并让某人猜测控制台中的代码。现在我的问题是我似乎无法找到替换代码中任何重复字符的方法。代码必须在" ABCDEF"范围内,并包含4个字母。这是我到目前为止所得到的:
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);
它打印的代码由2-3个字母组成,或者包含5或6个字母的代码,很少有正确的代码,包含4个字母。据我所知,这段代码的作用不是添加重复的字符,但是我希望它用另一个字符替换它们。有没有使用另一个随机生成的char来替换字符,而不使用Sets?
答案 0 :(得分:4)
听起来你只想在code
使用一次字母?为什么不使用ArrayList
从头开始设置,如果随机选择,则删除每个字符:
// copy `code` into a temporary arraylist
ArrayList<Character> possibleLetters = new ArrayList<Character>(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);
}
答案 1 :(得分:0)
import java.util.Random;
public class Main {
private static char[] code = new char[] { 'A', 'B', 'C', 'D', 'E', 'F'};
public static final void main(String[] args) {
char codeLetters;
String masterCode;
StringBuilder strings = new StringBuilder();
Random random = new Random();
while (strings.length() < 4) {
char tmpcode = code[random.nextInt(code.length)];
if (strings.toString().contains(tmpcode + "")) {
continue;
}
codeLetters = tmpcode;
strings.append(codeLetters);
}
masterCode = strings.toString();
System.out.println(masterCode);
}
}
用这个替换你的for循环然后你不需要做任何替换。 这只会插入字符串中尚未存在的字符。