Java学生GPA管理系统判断文件是否已加载及重复加载问题解决
问题根源
你当前的代码存在2个核心问题:
- 目前贴出的
OptionOne方法中没有提前判断logHistory是否已存在当前文件名的逻辑,只要文件存在就直接执行读取、打印加载成功、写入日志的操作。如果你之前自行添加了判断但还是会同时弹出两个提示,大概率是把判断逻辑写在了logHistory.add(input)之后,此时文件名已经被写入集合,判断自然永远为真,自然每次加载都会触发重复提示。除此之外该逻辑还会导致重复加载同一个文件时,studentList里会追加重复的学生数据。 printLog方法逻辑错误,会把所有日志内容重复打印N次(N等于已加载的文件数量)。
修复方案
1. 修复OptionOne方法的重复加载判断
在确认文件存在后,先判断文件名是否已在日志集合中,再决定是否要执行加载逻辑:
public static void OptionOne() throws FileNotFoundException { Scanner in = new Scanner(System.in); System.out.print("Enter the name of the class list or press 'B' to go back to the main menu.\n>>"); String input = in.next(); if (!input.equals("B")){ File File1 = new File("C:\\Users\\myName\\eclipse-workspace\\HW4\\" + input); if(File1.exists()) { // 把重复判断逻辑放在文件读取操作之前 if(logHistory.contains(input)){ System.out.println("File already loaded!"); return; } Scanner inFile = new Scanner(File1); while(inFile.hasNext()) { String inFirstName = inFile.next(); String inLastName = inFile.next(); float inGPA= Float.parseFloat(inFile.next()); Student stu = new Student(inFirstName, inLastName, inGPA); studentList.add(stu); } System.out.println(input + " loaded successfully!"); logHistory.add(input); } else { System.out.println("File does not exist!"); } } }
2. 修复printLog方法的打印逻辑
直接遍历集合打印每个元素即可,不需要转字符串替换括号:
public static void printLog() { for(String log : logHistory) { System.out.println(log); } }
内容的提问来源于stack exchange,提问作者Shane
相关产品推荐
相关产品推荐

