我想要一个java程序来计算文件中最常见的元素
答案 0 :(得分:1)
问题是“newCount”是String
而不是Integer
吗?
String newCount = entry.getValue().toString();
if(topN.containsKey(entry.getKey())){
newCount += topN.get(entry.getKey());
}
答案 1 :(得分:0)
使用行Parser parser;
,您声明了类Parser
的变量,但是您没有初始化该变量。请改用Parser parser = new Parser();
。
似乎也存在很多类型问题
String newCount = entry.getValue().toString();
if(topN.containsKey(entry.getKey())){
newCount += topN.get(entry.getKey());
}
topN.put(entry.getKey(), newCount);
您似乎想要计算累计数,但如果您先将Integer
转换为String
,这将无效!此外,key
的{{1}}将是一个值,因此Entry
永远不能包含该密钥,因为它是topN
Map
和{Strings
1}},即使是这样,您如何向Actors
(或Actor
)添加Integer
?最后,正如其他人所指出的那样,String
将失败,因为密钥的类型和值都与put
的类型不匹配。
如果不知道其他课程(Map
,Sketch
,Value
等)是做什么的,那么很难给出如何解决问题的明确建议。
答案 2 :(得分:0)
topN
被声明为Map<String, Actor>
。因此密钥必须为String
,且值必须为Actor
类型。
在topN.put(entry.getKey(), newCount);
中,newCount
(字符串)不是Actor
。另请检查entry.getKey()
是否为字符串。
public class Parser {
private BufferedReader bf;
private static final String ACTOR_MOVIE_FILE = "actormovie.txt";
private Map<String, Actor> actors;
//this is the input file size
int fileSize = ACTOR_MOVIE_FILE.length();
public Parser() {
try {
bf = new BufferedReader(new FileReader(ACTOR_MOVIE_FILE), 32768);
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "file cannot be located ", "File not found exception", JOptionPane.ERROR_MESSAGE);
}
actors = new Hashtable<String, Actor>(1713251);
}
/**
* this reads data on a line one at a time
* @return actors in the hash table, with the name of an actor as a,
* and value as the actor object
*/
public Map<String, Actor> readLines() {
String line=" ";
while(true){
try {
line = bf.readLine();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "deadlock file not in proper format", "we have error reading the file", JOptionPane.ERROR_MESSAGE);
}
if(line == null){
break;
}
String[] tokens = line.split("/");
assemblyLines(tokens);
}
try {
bf.close();
} catch(IOException e){
}
return actors;
}
/**
* from a line we get stringTokenizers parse to the data structures. Film is described as a
* stringTokenizer with film object created from it. There are actors which are as well
* stringTokenizers created as actor object
* there is an actor table that controls entry space. In occurrences of other actors ,
* the object is altered, other than that
* objected is created and appended to the table
* @param stringTokenizer makes the text file divided into individual components
*/
public void assemblyLines(String[] stringTokenizer){
Film film = new Film(stringTokenizer[0]);
for(int i = 1; i < stringTokenizer.length;i++){
Actor actor;
String actorName = stringTokenizer[i];
if(actors.containsKey(actorName)){
actor = actors.get(actorName);
} else {
actor = new Actor(actorName);
actors.put(actorName, actor);
}
film.addActor(actor);
actor.addFilm(film);
}
}
}