I am writing some code that is taking a user file and then sorting the information but I am having trouble writing the program so that if the user enters in the wrong file name the program wont just stop but give them another chance to enter the correct file.
I thought that I could do this with a do while that says ask for a file to read from repeatedly while the file does not exist but that didn't seem to work
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++;
}
}
}
When I try typing in a fake file that does not exist so that it asks for a file to read from again what I get is and exception. Example: File to read from: nothing.txt (this does not exist just want it to ask me again) then it gives me the exception below:
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)
You are trying to create a Scanner
with the file within the first do-while
loop, which leads to the FileNotFoundException
. So just do it after you have found a valid file as below.
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++;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.