gpt4 book ai didi

Java - 扫描仪拒绝关闭?

转载 作者:行者123 更新时间:2023-12-02 06:04:10 27 4
gpt4 key购买 nike

我创建了一个程序,它接受一个文件并分别输出该文件中的行数、单词数和字符数。

我的问题是,当我编译程序时,它被“卡住”,并且交互 Pane (或控制台)上没有输出任何内容。

while 循环应该终止,新的扫描仪对象应该覆盖旧的扫描仪对象。

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++;
}

关于Java - 扫描仪拒绝关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22426192/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com