Java实现文本文件随机替换指定字符:迷宫星号生成问题
解决迷宫中随机替换5个"0"为"*"的问题
看起来你已经完成了第一步(把所有现有*替换成0),接下来要实现的随机替换5个0的核心是先定位所有可替换的位置,再随机挑选不重复的位置进行修改。下面是修改后的完整代码,我会一步步解释关键逻辑:
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Random; public class MazeStarGenerator { public static void main(String[] args) { cheeseReset("maze.txt", "*", "0"); } static void cheeseReset(String filePath, String oldString, String newString) { File fileToBeModified = new File(filePath); String oldContent = ""; BufferedReader reader = null; FileWriter writer = null; try { // 读取文件内容到oldContent reader = new BufferedReader(new FileReader(fileToBeModified)); String line = reader.readLine(); while (line != null) { oldContent = oldContent + line + System.lineSeparator(); line = reader.readLine(); } // 第一步:把所有*替换成0 String newContent = oldContent.replace(oldString, newString); // 第二步:随机替换5个0为* char[] contentChars = newContent.toCharArray(); List<Integer> zeroIndices = new ArrayList<>(); // 收集所有'0'的索引位置 for (int i = 0; i < contentChars.length; i++) { if (contentChars[i] == '0') { zeroIndices.add(i); } } // 检查可用的0数量是否足够5个,避免报错 if (zeroIndices.size() >= 5) { Random random = new Random(); // 随机挑选5个不重复的索引 for (int i = 0; i < 5; i++) { // 从剩余的0索引中随机选一个 int randomIndex = random.nextInt(zeroIndices.size()); int targetPos = zeroIndices.get(randomIndex); // 替换成* contentChars[targetPos] = '*'; // 移除已选的索引,避免重复替换 zeroIndices.remove(randomIndex); } // 把字符数组转回字符串 newContent = new String(contentChars); } else { System.err.println("错误:迷宫中可用的0数量不足5个,无法完成替换"); } // 写入修改后的内容到文件 writer = new FileWriter(fileToBeModified); writer.write(newContent); } catch (IOException e) { e.printStackTrace(); } finally { // 确保流关闭 try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e) { e.printStackTrace(); } } } }
关键逻辑解释:
- 转成字符数组:字符串是不可变的,转成
char[]可以直接修改单个字符,效率更高。 - 收集0的索引:遍历字符数组,把所有是
0的位置存到列表里,这样我们就知道所有可以替换的候选位置。 - 随机挑选不重复位置:用
Random.nextInt()从候选列表中随机选索引,选完后立即移除该索引,避免重复替换同一个位置。 - 边界检查:先判断候选列表的长度是否≥5,防止因为迷宫里0太少而抛出
IndexOutOfBoundsException。
这样每次运行程序时,都会随机挑选5个不同的0位置替换成*,完全符合你的需求。
内容的提问来源于stack exchange,提问作者Steven Elcarim
相关产品推荐
相关产品推荐

