提问人:David 提问时间:11/3/2022 更新时间:11/3/2022 访问量:72
程序在 While 循环运行期间冻结
Program freezes during run at While loop
问:
我正在编写的程序需要从包含员工 ID、姓名、级别和薪水的文本文件中读取 4 行数据。然后,它需要创建一个格式化的电子邮件地址,并将所有这些内容打印到标准输出。文本文件可能包含未知数量的员工,因此必须将 while 循环与 hasNext() 方法一起使用,以确认有更多数据要读取。
我的程序在while循环开始时立即冻结(使用Java博士),我无法弄清楚原因。
这是我到目前为止的代码
public static void main(String[] args) 抛出 IOException {
File file = new File("employeeInput.txt");
if (file.exists()) { //check if file exists
Scanner inputFile = new Scanner(file); //opens file
String companyName = inputFile.nextLine();
System.out.println(companyName);
System.out.println();
System.out.println("----------------------------");
while (inputFile.hasNext()); {
String studentID = inputFile.nextLine();
System.out.println(studentID);
String studentName = inputFile.nextLine();
System.out.println(studentName);
String employeeLevel = inputFile.nextLine();
System.out.println(employeeLevel);
double salary = inputFile.nextDouble();
System.out.println(salary);
}
inputFile.close();
}
else {
System.out.println("The file employeeInput.txt does not exist");
}
}
}
我知道这段代码并不完整,并且可以完成程序需要的所有操作,但我不明白为什么它在 while 循环中冻结。
任何帮助或建议将不胜感激。这是我的第一堂编程语言课,所以请放轻松:)
答: 暂无答案
评论
while (inputFile.hasNext());
这本身就是一个循环。分号表示你有一个空的循环体......并且看到你没有消耗任何东西,如果它从返回 true 开始,它将继续返回 true。如果希望分号后面的大括号指示“这是循环主体的开始”,则应删除分号。inputFile
hasNext