gpt4 book ai didi

java - 打印外部文件的内容

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:25 26 4
gpt4 key购买 nike

下面是我的家庭作业代码,我需要读取外部文件的内容并确定其中的单词数、3 个字母单词的数量以及总数的百分比。我已经把这部分写下来了,但是在显示上述信息之前我还必须打印外部文件的内容。以下是我当前的代码:

public class Prog512h 
{
public static void main( String[] args)
{
int countsOf3 = 0;
int countWords = 0;

DecimalFormat round = new DecimalFormat("##.00"); // will round final value to two decimal places

Scanner poem = null;
try
{
poem = new Scanner (new File("prog512h.dat.txt"));
}
catch (FileNotFoundException e)
{
System.out.println ("File not found!"); // returns error if file is not found
System.exit (0);
}

while (poem.hasNext())
{
String s = poem.nextLine();
String[] words = s.split(" ");
countWords += words.length;
for (int i = 0; i < words.length; i++)
{
countsOf3 += words[i].length() == 3 ? 1 : 0; // checks for 3-letter words
}
}

while(poem.hasNext())
{
System.out.println(poem.nextLine());
}
System.out.println();
System.out.println("Number of words: " + countWords);
System.out.println("Number of 3-letter words: " + countsOf3);
System.out.println("Percentage of total: " + round.format((double)((double)countsOf3 / (double)countWords) * 100.0)); // converts value to double and calculates percentage by dividing from total number of words
}

}

声明

while(poem.hasNext()) 
{
System.out.println(poem.nextLine());
}

应该打印外部文件的内容。然而,事实并非如此。当我尝试在之前的 while 循环之前移动它时,它会打印,但会搞乱我的单词数、3 个字母单词、百分比等的打印值。我不太确定这里的问题是什么。有人可以提供一些帮助吗?

提前谢谢您。

最佳答案

您的扫描仪正在尝试重新读取该文件,但该文件位于底部,因此没有更多行可供读取。您有两个选择:

选项 1

为同一个文件创建一个新的 Scanner 对象(再次从头开始),然后对该文件调用 while 循环(可以工作,但不是一个很好的设计)。

Scanner poem2 = null;
try
{
poem2 = new Scanner (new File("prog512h.dat.txt"));
}
catch (FileNotFoundException e)
{
System.out.println ("File not found!"); // returns error if file is not found
System.exit (0);
}

while(poem2.hasNext())
{
System.out.println(poem2.nextLine());
}

选项 2

更好的选择是在读入时显示每一行。这可以通过向已存在的 while 循环添加额外的行来完成:

while (poem.hasNext()) 
{
String s = poem.nextLine();
System.out.println(s); // <<< Display each line as you process it
String[] words = s.split(" ");
countWords += words.length;
for (int i = 0; i < words.length; i++)
{
countsOf3 += words[i].length() == 3 ? 1 : 0; // checks for 3-letter words
}
}

这仅需要一个 Scanner 对象,并且只需要一次读取文件,效率更高。

关于java - 打印外部文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27466277/

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