gpt4 book ai didi

java - 在 Java 中读取输入文件

转载 作者:行者123 更新时间:2023-11-30 06:55:07 24 4
gpt4 key购买 nike

这个程序的目的是读取输入文件并解析它以查找单词。我使用一个类和实例化的对象来保存每个唯一的单词以及在输入文件中找到的该单词的计数。例如,对于一个句子,“Word”被找到一次,“are”被找到一次,“fun”被找到两次,...该程序忽略数字数据(例如 0、1...)以及标点符号(像 . , ; : - )

赋值不允许使用固定大小的数组来保存单词字符串或计数。无论输入文件的大小如何,该程序都应该工作。

我收到以下编译错误:低于 1.7 的源代码级别不允许使用“<>”运算符 [行:9]

import java.io.*;
import java.util.*;

public class Test {

public static void main(String args[]) throws IOException {


HashMap<String,Word> map = new HashMap<>();

// The name of the file to open.
String fileName = "song.txt";

// This will reference one line at a time
String line = null;

try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);

// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);

while((line = bufferedReader.readLine()) != null) {

String[] words = line.split(" ");

for(String word : words){
if(map.containsKey(word)){
Word w = map.get(word);
w.setCount(w.getCount()+1);
}else {
Word w = new Word(word, 1);
map.put(word,w);
}
}
}

// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}



for(Map.Entry<String,Word> entry : map.entrySet()){
System.out.println(entry.getValue().getWord());
System.out.println("count:"+entry.getValue().getCount());
}
}

static class Word{

public Word(String word, int count) {
this.word = word;
this.count = count;
}

String word;
int count;

public String getWord() {
return word;
}

public void setWord(String word) {
this.word = word;
}

public int getCount() {
return count;
}

public void setCount(int count) {
this.count = count;
}
}

}

最佳答案

您要么需要使用 1.7 或更高版本的 JDK 进行编译,要么更改以下行:

HashMap<String,Word> map = new HashMap<>();

HashMap<String,Word> map = new HashMap<String,Word>();

关于java - 在 Java 中读取输入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35709136/

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