如何从用户输入java中查找和打印文本文件中的重复单词
当我运行程序时,我想在文本文件中输入一个单词,并让它打印出单词在文本中存储了多少次。例如:
从文本中输入一个单词:eric
eric一词在文本文件中存储了5次
我下面的代码已经读取了文本文件,但我仍然坚持使用wordCount方法。我不知道怎么开始
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
public class WordSet {
private static Scanner file;
private static ArrayList<String> words = new ArrayList<String>();
//private static Map<String, Integer> occurences = new HashMap<String, Integer>();
//private static Set<String> uniqueWords = new HashSet<String>(words);
//private static int tWords = 0;
//private static int uWords = 0;
//private static String [] word1 = new String[10];
//private static String [] word2 = new String[10];
public static void openFile() throws IOException {
try {
file = new Scanner(new File("words.txt"));
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
e.printStackTrace();
} catch (Exception e) {
System.out.println("IOException");
}
}
public static String wordCount() throws IOException {
Random r = new Random();
while(file.hasNext()) {
words.add(file.next());
}
String wordCount = words.get(r.nextInt(words.size()));
return wordCount;
}
public static void main(String[] args) throws IOException {
System.out.println("Enter a word from the text: ");
openFile();
Scanner scan = new Scanner(System.in);
String pickWord = wordCount();
while(scan.hasNext()) {
String input = scan.nextLine();
if(input.equals(pickWord)) {
System.out.println(pickWord);
}
}
scan.close();
}
}
# 1 楼答案
# 2 楼答案
我已经添加了从命令行获取的输入,并读取了ArrayList,以给出下面的freq代码片段
Bu使用集合。frequency()u可以用更少的代码轻松计数…:)