是否有可能从while循环内部返回值?我需要返回名称值。这是我的代码:
public static String askFileName() {
Scanner scanner = new Scanner(System.in);
boolean flag = true;
while (flag) {
System.out.print("Type a file name: ");
String name = scanner.nextLine();
File file = new File(name);
try {
Scanner scanner1 = new Scanner(file);
break;
} catch (FileNotFoundException e) {
flag = true;
}
return null // ???;
}
}
谢谢!
答案 0 :(得分:0)
您可以尝试下面的内容
public static String askFileName()
{
Scanner scanner = new Scanner(System.in);
String temp = null;
boolean flag = true;
while (flag)
{
System.out.print("Type a file name: ");
String name = scanner.nextLine();
File file = new File(name);
try
{
Scanner scanner1 = new Scanner(file);
temp = name;
flag = false;
}
catch (FileNotFoundException e)
{
flag = true;
temp = null;
}
}
return temp; //return value here
}