我正在编写一些代码,该代码获取用户文件,然后对信息进行排序,但我在编写程序时遇到了麻烦,这样如果用户输入错误的文件名,程序将不会停止,而是给他们另一次输入的机会正确的文件。
我认为我可以用 do while 来做到这一点,它要求文件不存在时重复读取该文件,但这似乎不起作用
public void readText(int ages[], String names[]) throws FileNotFoundException{
String filename = "";
Scanner inputFile = new Scanner(System.in);
do {
System.out.println("File to read from:");
filename = inputFile.nextLine();
File file = new File(filename);
inputFile = new Scanner(file);
}
while (!new File(filename).exists());
while (inputFile.hasNextLine()) {
String data = inputFile.nextLine();
String[] parts = data.split("(?<=\\))(?=\\()");
for (String part : parts) {
String input = part.replaceAll("[()]", "");
ages[count] = Integer.parseInt(input.split(", ")[0]);
names[count] = input.split(", ")[1];
count++;
}
}
}
当我尝试输入一个不存在的假文件,以便它要求再次读取一个文件时,我得到的是异常。 例子: 要读取的文件: Nothing.txt(这个不存在只是想让它再次询问我) 然后它给了我以下异常(exception):
Exception in thread "main" java.io.FileNotFoundException: nothing.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at PonySort.readText(PonySort.java:95)
at PonySort.main(PonySort.java:30)
最佳答案
您尝试在第一个 do-while
循环中使用该文件创建一个 Scanner
,这会导致 FileNotFoundException
。因此,请在找到有效文件后执行此操作,如下所示。
public void readText(int ages[], String names[]) throws FileNotFoundException{
String filename = "";
Scanner inputFile = new Scanner(System.in);
File file;
do {
System.out.println("File to read from:");
filename = inputFile.nextLine();
file = new File(filename);
} while (!file.exists());
inputFile = new Scanner(file);
while (inputFile.hasNextLine()) {
String data = inputFile.nextLine();
String[] parts = data.split("(?<=\\))(?=\\()");
for (String part : parts) {
String input = part.replaceAll("[()]", "");
ages[count] = Integer.parseInt(input.split(", ")[0]);
names[count] = input.split(", ")[1];
count++;
}
}
}
关于java - 我在 do while 循环中遇到问题,要求用户提供新文件,而前一个文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58176950/