【发布时间】:2014-12-14 04:12:05
【问题描述】:
下面是我的家庭作业代码,我需要读取外部文件的内容并确定其中的单词数、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 个字母单词、百分比等值。我不太确定这里有什么问题。有人可以提供一些帮助吗?
提前谢谢你。
【问题讨论】:
-
感谢您的及时建议!我只是试图在没有运气的情况下实现它。内容仍然不打印。 :(
标签: java external file-handling file-read