Java方法判断字符串是否存在于文本文件时逻辑异常求助
问题分析与修复方案
核心问题点
- 读取内容不完整:
fileScanner.next()只会读取到空格/换行符前的单个片段,而非文件中的完整一行,导致匹配逻辑拿不到正确的对比内容。 - 循环逻辑过早终止:不管第一行是否匹配,循环都会直接break,根本没机会检查文件里的其他行,自然永远走else分支。
- 拼写错误:方法名
ChcekIfPasswordExsists、提示文本里的exsits都是拼写错误,虽不影响运行,但降低了代码可读性。 - 资源未释放:BufferedReader 和 Scanner 使用后未关闭,存在资源泄漏风险。
修复后的代码
// 修正方法名拼写 public void checkIfPasswordExists(String check) throws FileNotFoundException { // 用try-with-resources自动关闭流,无需手动处理 try (BufferedReader reader = new BufferedReader(new FileReader("Passwords.txt")); Scanner fileScanner = new Scanner(reader)) { boolean isFound = false; while (fileScanner.hasNextLine()) { // 读取文件完整一行内容 final String line = fileScanner.nextLine(); if (line.contains(check)) { System.out.println("Password for " + check + " already exists"); isFound = true; break; // 找到匹配项后终止循环 } } // 遍历完所有行后,确认未匹配再输出可用提示 if (!isFound) { System.out.println(check + " is usable"); } } }
调用代码修正(原代码存在字符串换行语法错误)
System.out.println("Enter the name of the app or website, where password is going to be used:"); useCase = s.nextLine(); checkIfPasswordExists(useCase); // 调用修正后的方法名
关键修复说明
- 读取整行内容:用
fileScanner.nextLine()替代fileScanner.next(),确保获取文件中的完整一行,避免因空格截断导致匹配失败。 - 调整判断逻辑:先遍历所有行查找匹配项,仅当循环结束确认无匹配时,才输出“可用”提示,避免第一行不匹配就直接下结论。
- 自动释放资源:try-with-resources语法会在代码块结束时自动关闭流,避免手动关闭可能出现的遗漏。
- 修正拼写错误:统一修正方法名和文本中的拼写问题,提升代码规范性。
内容的提问来源于stack exchange,提问作者robinyg
相关产品推荐
相关产品推荐

