-1

有没有办法使用try/catch语句让用户输入一个文件,如果用户输入了错误的文件名,程序会再问两次,然后异常退出?我怎么能循环?因为一旦用户输入了错误的文件名,程序就会立即抛出异常。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {
    static String[] words = new String[5];
    public static void main(String[] args)
    {
        Scanner kb = new Scanner(System.in);

        System.out.println("enter file name:");
        String fileName = kb.next();

        try {

            File inFile = new File(fileName);
            Scanner in = new Scanner(new File(fileName));

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }    

    } 
4

3 回答 3

2

所以你不希望它在用户输入错误的文件名时抛出任何类型的错误,对吧?如果是这样,那么我认为这就是您想要的:

for(int i = 0; i < 3; i++){
        try {
            File inFile = new File(fileName);
            Scanner in = new Scanner(new File(fileName));
            break;
        } catch (FileNotFoundException ex) {
            if(i == 2){
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                System.exit(0);
            }
            else
                continue;
        }
    }

如果用户输入正确的文件名,它将跳出循环。如果不是,它会检查循环是否在第三次迭代中。如果是,(这意味着用户已经尝试过两次但都失败了),它会打印错误并退出程序。如果循环不在第三次迭代中,它会继续循环并重新提示用户。

于 2012-07-13T00:42:54.840 回答
0

假设您创建了一个布尔值 fileIsLoaded = false,并将其设置为 true。您可以创建一个循环

for(int i=0;i<2 && !fileIsLoaded; i++) {
//your try/catch goes here
} 

将当前 main 中的所有代码包含在该循环中(使用预先创建的布尔值)。最后,您可以在之后检查布尔值,以防所有尝试都失败。

于 2012-07-13T00:37:36.613 回答
0

我希望很明显 FileNotFoundException 是由 Scanner 构造函数抛出的。那么在确定文件存在之前为什么要使用它呢?在获得正确的文件之前,您不应该创建 Scanner 对象!要实现这个想法,请在您的 try 块中使用:

//read file name from stdio
File inFile = new File(fileName);
int i = 0;
while(!inFile.exists() && i++ < 2 ){
        //read file name from System.in;
        inFile = new File(fileName);
}
Scanner in = new Scanner(new File(fileName));
于 2012-07-13T00:42:34.253 回答