我正在尝试创建一个程序,用#34; *"替换随机位置的随机字符数。 Star是主程序中使用的字母,用"替换。"一个通配符,用于匹配任何可能的结果。
到目前为止,我设法创建您看到的代码。它恰好取代了特定单词的1个字符。 现在任何帮助都将非常感激。
示例:
输入字:MOUSE
RANDOM GENERATOR用于替换多少字符:3
RANDOM GENERATOR,替换位置:1,3,5
结果:* O * S *
public class random_2 {
public static void main(String[] args) {
String test;
int dolzina = 0;
String outputFile = "random_2.txt";
ArrayList<String> list = new ArrayList();
try {
File file = new File("random1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica;
while ((vrstica = bufferedReader.readLine()) != null) {
list.add(vrstica);
// dolzina=list.size();
// System.out.println(dolzina);
}
FileWriter fileWriter = new FileWriter(outputFile);
PrintWriter out = new PrintWriter(fileWriter);
for (int idx = 0; idx <= list.size(); ++idx) {
test=list.get(idx);
dolzina=test.length();
Random rGenerator = new Random();
for (int i = 0; i<= dolzina; ++i) {
int randomInt = rGenerator.nextInt(dolzina);
StringBuilder beseda = new StringBuilder(test);
beseda.setCharAt(randomInt, '*');
System.out.println(beseda);
dolzina=0;
}}
System.out.println("Done.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
String mask(String s, int charsToMask){
if(s.length() < charsToMask) throw new IllegalArgumentException();
List<Integer> shuffle = new ArrayList<>(s.length())
for (int i = 0; i < s.length(); i++) {
shuffle.add(i, i);
}
Collections.shuffle(shuffle);
StringBuilder sb = new StringBuilder(s)
for (int i = 0; i < charsToMask; i++) {
sb.setCharAt(shuffle.get(i).intValue(), (char)'*')
}
return sb.toString()
}
print mask("MOUSE", 3)
答案 1 :(得分:0)
修改了您的代码及其工作原理:
try {
File file = new File("random1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica = bufferedReader.readLine();
while (vrstica != null) {
list.add(vrstica);
vrstica = bufferedReader.readLine();
// dolzina=list.size();
// System.out.println(dolzina);
}
FileWriter fileWriter = new FileWriter(outputFile);
PrintWriter out = new PrintWriter(fileWriter);
for (int idx = 0; idx < list.size(); ++idx) {
test = list.get(idx);
dolzina = test.length();
Random rGenerator = new Random();
StringBuilder beseda = new StringBuilder(test);
for (int i = 0; i < dolzina; ++i) {
int randomInt = rGenerator.nextInt(dolzina);
beseda.setCharAt(randomInt, '*');
System.out.println(beseda);
}
out.print(beseda);
out.close();
}