Java-Scanner拒绝关闭?
我创建了一个程序,它接收一个文件并分别输出该文件中的行数、字数和字符数 我的问题是,当我编译程序时,它被“卡住”,在交互窗格(或控制台)上没有输出任何内容 while循环应该终止,新的扫描器对象应该超过旧的扫描器对象Java-Scanner拒绝关闭?,java,file,Java,File,我创建了一个程序,它接收一个文件并分别输出该文件中的行数、字数和字符数 我的问题是,当我编译程序时,它被“卡住”,在交互窗格(或控制台)上没有输出任何内容 while循环应该终止,新的扫描器对象应该超过旧的扫描器对象 public static void main(String[] args) throws FileNotFoundException { String[] filenames = new String[]{"cat.txt", "dog.txt", "mouse.txt
public static void main(String[] args) throws FileNotFoundException
{
String[] filenames = new String[]{"cat.txt", "dog.txt", "mouse.txt", "horse.txt"} ;
int totalLines = 0, totalWords = 0, totalCharacters = 0 ;
for (String filename : filenames)
{
int lines = 0, words = 0, characters = 0;
try {
Scanner scanner_lines = new Scanner (new File(filename)); //Reading Lines
while (scanner_lines.hasNextLine()){
lines++;
}
scanner_lines.close();
Scanner scanner_words = new Scanner (new File(filename)); //Reading Words
while (scanner_words.hasNext()){
words++;
}
scanner_words.close();
Scanner scanner_chars = new Scanner (new File(filename)); //Reading Characters
scanner_chars.useDelimiter("");
while (scanner_chars.hasNext()){
characters++;
}
scanner_chars.close();
} // end of try
catch (FileNotFoundException e) {}
System.out.println (lines + " " + words + " " + characters);
}
}
循环需要消耗线,而不仅仅是确定它的存在:
Scanner scanner_lines = new Scanner (new File(filename)); //Reading Lines
while (scanner_lines.hasNextLine()){
scanner_lines.nextLine(); // this is critical
lines++;
}
你确定它卡住了吗?或者它只是在输入catch(FileNotFoundException e){}?您应该始终记录异常,空捕获是一种极度疯狂的行为。为什么
尝试捕获aFileNotFoundException
如果您的函数已经可以抛出一个异常,并且在找不到文件时您也不做任何事情,您确定程序可以找到它们吗?因此它不会隐式迭代吗?不,hesNextLine()
只是告诉您如果有下一行,您必须先阅读该行才能阅读,然后再转到另一行。