該程序的目的是讀取輸入文件並解析它尋找單詞。我使用了一個類和實例化對象來保存每個唯一的單詞以及在輸入文件中找到的單詞的計數。例如,對於一個句子「Word」被找到一次,「are」被找到一次,「fun」被找到兩次,...該程序忽略數字數據(例如0,1,...)以及標點符號諸如:,;: - )閱讀Java中的輸入文件
賦值不允許使用固定大小的數組來保存字符串或計數。無論輸入文件的大小如何,程序都可以工作。
我正在以下編譯錯誤: '<>' 操作者不允許源水平低於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;
}
}
}
你已經改變文件名的價值任何機會,從你貼什麼?該錯誤表明它將名稱視爲一個URL並遇到一些解析錯誤。錯誤來自文件打開或其他一些代碼行嗎? –