【发布时间】:2021-03-20 09:05:39
【问题描述】:
我应该编写一个程序来读取名为 mobydick.txt 的文件。该文件包含《白鲸记》这本书的全文。 The mobydick.txt file looks like this
我必须读取文件,显示文件中的每个唯一单词,然后显示每个唯一单词的出现次数。
输出应如下所示:
字数
43
鲸鱼 12
93 号船
这是我目前的代码:
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
//Create input stream & scanner
FileInputStream fin = new FileInputStream("mobydick.txt");
Scanner fileInput = new Scanner(fin);
//Create Arraylist
ArrayList<String> words = new ArrayList<String>();
ArrayList<Integer> count = new ArrayList<Integer>();
//Read through file and find the words
while(fileInput.hasNext())
{
//Get next word
String nextWord = fileInput.next();
//Determine if the word is in the arraylist
if(words.contains(nextWord))
{
int index = words.indexOf(nextWord);
count.set(index, count.get(index) + 1);
}
else
{
words.add(nextWord);
count.add(1);
}
}
//close
fileInput.close();
fin.close();
System.out.println("WORDS COUNT");
//Print out the results
for(int i = 0; i < words.size(); i++)
{
System.out.print(words.get(i) + " " + count.get(i) + "\n");
}
}
}
但是,当我运行此代码时,output 看起来很奇怪。
这很奇怪,因为如果我为像this 这样更小更简单的文本文件运行相同的代码,输出看起来像exactly like I want it to。
mobydick.txt 我做错了什么?
【问题讨论】:
-
使用 HashMap
-
您使用什么 IDE?我认为这很重要。我认为扫描仪没有读取 UTF-8 的东西(顺便说一句:你有 Top、mid、jug 和 bot...但是没有 sup?)
-
请不要只将结果/数据/代码发布为图片。看起来您的输入文件存在字符编码问题。