[英]I am having trouble with my do while loop for asking a user for a new file is the previous one does not work
我正在編寫一些獲取用戶文件然后對信息進行排序的代碼,但是我在編寫程序時遇到了麻煩,因此如果用戶輸入了錯誤的文件名,程序不會停止,而是給他們另一個機會輸入正確的文件.
我想我可以用 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 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++;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.