循环时程序不会进入try块

hit*_*j47 1 java loops exception try-catch while-loop

我正在努力为学校写一个程序.分配是循环并要求用户输入文件.当找不到文件或者用户退出循环时(在我的情况下,他们点击joptionpane上的取消)输出每个文件的数据.到目前为止这是我的代码:

/**
 * @param args
 */
public static void main(String[] args) {

    // Lists to hold file data
    List<String> fileNames = new ArrayList<String>();
    List<Integer> numChars = new ArrayList<Integer>();
    List<Integer> numWords = new ArrayList<Integer>();
    List<Integer> numLines = new ArrayList<Integer>();
    String inFile;

    while ( (inFile = JOptionPane.showInputDialog("Enter a file name:")) != null) {

        // Create new file object instance
        File file = new File(inFile);

        try {
            fileNames.add(inFile);  // File name as a string
            // Pass file objects
            numChars.add( getNumChars(file));
            numWords.add( getNumWords(file));
            numLines.add( getNumLines(file));
            System.out.println("entered try block");
        } catch(FileNotFoundException e) {
            System.out.println("Could not find file: " + inFile);
            // break out the loop and display data
            break;
        }
    }   // end while

    if (numChars.size() > 0)
        showFileData(fileNames, numChars, numWords, numLines);

    System.out.println("Program ended");

}

private static void showFileData(List<String> fileNames,
        List<Integer> numChars, List<Integer> numWords,
        List<Integer> numLines) {
    for (int i=0;i<numChars.size();i++) {
        System.out.println("Data for: " + fileNames.get(i));
        System.out.println("Number of characters: " + numChars.get(i));
        System.out.println("Number of words: " + numWords.get(i));
        System.out.println("Number of lines: " + numLines.get(i));
        System.out.println("-----------------------------------------------");
    }

}

private static int getNumLines(File file) throws FileNotFoundException {
    int c = 0;
    Scanner f = new Scanner(file);
    while(f.hasNextLine()) {
        c++;
    }
    return c;
}

private static int getNumWords(File file) throws FileNotFoundException {
    int c = 0;
    Scanner f = new Scanner(file);
    while (f.hasNextLine()) {
        String[] w = f.nextLine().split(" ");
        c += w.length;
    }
    return c;
}

private static int getNumChars(File file) throws FileNotFoundException {
    Scanner f = new Scanner(file);
    int c = 0;
    String line;
    while(f.hasNextLine()) {
        line = f.nextLine();
        String[] s = line.split(" ");
        for (int i=0;i<s.length;i++) {
            c += s[i].length();
        }
    }
    return c;
}
Run Code Online (Sandbox Code Playgroud)

当我运行程序时,如果我按下取消,它会退出循环并在结束时显示这些内容.如果我输入一个不存在的文件,它将按照预期的方式工作.它唯一不起作用的是当我输入一个存在的文件时,它不会弹出另一个输入对话框.实际上,它似乎没有进入try块.我是否正确设置了我的程序?

小智 5

你有一个无限循环getNumLines().你需要一个f.nextLine()while循环.