我正在尝试为学校编写一个程序。任务是循环并要求用户输入文件。当找不到文件或用户退出循环(在我的情况下,他们单击 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;
}
当我运行程序时,如果我按下取消,它会退出循环并在最后显示内容,就像它应该的那样。如果我输入一个不存在的文件,它会按预期工作。唯一不起作用的是当我输入一个确实存在的文件时,它不会弹出另一个输入对话框。事实上,它似乎并没有进入 try 块。我是否正确设置了我的程序?