下面是我的家庭作业代码,我需要阅读外部文件的内容并确定其中的单词数,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个字母的单词,百分比等等。我不确定这里的问题是什么。有人可以提供一些帮助吗?
提前谢谢。
答案 0 :(得分: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());
}
更好的选择是在读取时显示每一行。这可以通过在已存在的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
对象,只需要对文件进行一次通读,效率更高。