我正在尝试制作一个程序,如果它存在,它将读取文件。如果该文件不存在,那么我希望它循环回来并再次询问用户输入。目前我已经知道它会停止但是我想让它循环回来再问一下,有什么想法吗?
System.out.println("Enter the file you want to check (without file extension): ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String in = (input + ".txt");
File f = new File(in);
if(!f.exists()) {
System.out.println(in + " doesn't exist! Try again.");
return;
}
String fileName = input;
String content = readFile(in);
System.out.println(content);
答案 0 :(得分:3)
一种方法是使用do
,while(false)
循环(允许f
限定为循环体):
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Enter the file you want to check (without file extension): ");
String input = scanner.nextLine();
String in = (input + ".txt");
File f = new File(in);
if(!f.exists()){
System.out.println(in + " doesn't exist! Try again.");
continue; /*go round again*/
}
} while (false/*i.e. exit the loop if we get here*/);
如果您希望循环后f
可用,则在File f;
行之前声明do {
,并在循环体中写f = new File(in);
。
答案 1 :(得分:1)
只是为您提供更经典的while
循环来执行此操作。
请注意@Bathsheba的回答非常简洁,你绝对应该接受他的回答。
System.out.println("Enter the file you want to check (without file extension): ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String in = (input + ".txt");
File file = new File(input);
while(!file.exists()){
System.out.println(in + " doesn't exist! Try again.");
input = scanner.nextLine();
in = (input + ".txt");
file = new File(input);
}
答案 2 :(得分:0)
我不喜欢do
- while
和while(false)
甚至while(true)
和break
。
如果没有太多工作,我会做类似的事情:
Scanner scanner = new Scanner(System.in);
File f = getFile();
while (!f.exist()) {
f = getFile();
}
private File getFile() {
System.out.println("Enter the file you want to check (without file extension): ");
String input = scanner.nextLine();
String in = (input + ".txt");
File f = new File(in);
if (!f.exists()) {
System.out.println(in + " doesn't exist! Try again.");
}
return f;
}
这避免了丑陋的do-while循环,并且很好地封装了获取逻辑。您理论上也可以使其递归(尽管允许堆栈溢出)或让它返回Pair
File, in
,它会将输入提升到外部循环,从而允许循环访问{{ 1}}变量。