Java程序每次运行读取不同文本文件异常:始终进入else分支求助
问题原因及解决方案
你的代码始终进入else分支的核心问题是:File.toString()返回的是文件的完整路径字符串(比如当前目录下会是./matrix1.txt或系统相关的完整路径),而非单纯的文件名matrix1.txt,导致字符串匹配永远不成立,逻辑只能走到else分支。
修复方案1:直接用随机数判断(简洁高效)
无需通过文件对象的字符串判断,直接用生成的randomNum做分支,彻底避免路径匹配问题:
int min = 1; int max = 2; int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1); File file; if(randomNum == 1) { System.out.println("Input filename: matrix1.txt"); file = new File("matrix1.txt"); } else if(randomNum == 2) { System.out.println("Input filename: matrix2.txt"); file = new File("matrix2.txt"); } else { System.out.println("Input filename: matrix.txt"); file = new File("matrix.txt"); }
修复方案2:用File.getName()获取纯文件名
如果坚持通过文件对象判断,改用file.getName()获取仅含文件名的字符串(不含路径):
int min = 1; int max = 2; int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1); File file = new File("matrix" + randomNum + ".txt"); if(file.getName().equals("matrix1.txt")) { System.out.println("Input filename: matrix1.txt"); } else if(file.getName().equals("matrix2.txt")) { System.out.println("Input filename: matrix2.txt"); } else { System.out.println("Input filename: matrix.txt"); file = new File("matrix.txt"); }
额外优化建议
可以把文件名存入数组,通过随机索引直接获取,代码更简洁且扩展性更强(后续新增文件只需往数组里添加):
String[] filenames = {"matrix.txt", "matrix1.txt", "matrix2.txt"}; int randomIndex = ThreadLocalRandom.current().nextInt(filenames.length); File file = new File(filenames[randomIndex]); System.out.println("Input filename: " + filenames[randomIndex]);
内容的提问来源于stack exchange,提问作者Codrunnr
相关产品推荐
相关产品推荐

