这是我编写的和平代码:
double value;
String fileName;
Scanner readFile;
Scanner reader=new Scanner(System.in);
System.out.println("Enter a file name:");
fileName=reader.next();
reader.close();
try{
readFile=new Scanner(new FileReader(fileName));
value=readFile.nextDouble();
readFile.close();
}
catch(FileNotFoundException e){
System.err.println("\n The file doen't exist");
}
然后在Catch块中,我想无限次地询问用户一个有效的文件名,直到他输入一个文件名为止。如果他再次输入了无效的文件名,请使用Try-Catch引发同等的异常。我该怎么做?谢谢
您在应用程序中缺少循环的概念。
当您的应用程序期望重复某些行为/动作时。您应该将其包含在循环中。有两个回路提供一个for
和while
。
当之前知道操作数并且使用迭代器进行操作时,将使用for循环。
当您不知道何时会发生某些操作而只是等待时,将使用while循环。
boolean shouldRetry = true;
while(shouldRetry) {
try {
action();
shouldRetry= false;
} catch(Exception e) {
shouldRetry= true;
}
}
在您的情况下,需要do while
循环,因为您不知道用户何时提供有效的输入数据。确保至少应执行一次该操作。
boolean shouldRetry= false;
do {
try {
action();
shouldRetry= false;
} catch(Exception e) {
shouldRetry= true;
}
}while(shouldRetry)
的condition
必须是一个布尔表达式。它确定应执行的操作。
编辑:
如果可能的话,您应该尝试将代码中的动作分隔为不同的方法。
Scanner reader = new Scanner(System.in);
do {
System.out.println("Enter a file name:");
} while(!processFile(reader.next())); //Read the file name
reader.close();
/**
* @return true if file read with success otherwise false.
*/
private boolean processFile(String fileName) {
try {
//read the file
}catch(Exception e) {
return false;
}
return true;
}
这使您的行为更加灵活。这样,您可以在文件无效时重试,这不仅是因为它不存在,而且还可能是因为它不具有您期望的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句