我很好奇,如果我正在從這個文件中讀取正確的文本。Java - 我是否正確地從這個文件中讀取文本?
目的:從文件中讀取文本,並將其放置到一個名爲集「線」(一組是LinkedHashSet因爲我應該在加入他們的順序排序的元素)。
這裏是從main()函數的代碼(省略進口):
public class Main {
public static void main(String[] args) {
try {
Set<FileExaminer> examiners = new LinkedHashSet<>();
examiners.add(new FileExaminer("raven.txt"));
examiners.add(new FileExaminer("jabberwocky.txt"));
for (FileExaminer fe : examiners) {
System.out.println("-----------------------");
fe.display(45);
System.out.println();
fe.displayCharCountAlpha();
fe.displayCharCountNumericDescending();
}
}catch(FileNotFoundException e){
System.out.println(e.getMessage());
}
}
}
這裏是LinkedHashSet的創作:
private LinkedHashSet<String> lines = new LinkedHashSet<>();
下面是從代碼正在此處引用FileExaminer類:
public FileExaminer(String filename) throws FileNotFoundException {
File file = new File(file);
if(file.exists()){
Scanner reader = new Scanner(filename);
/** Read the contents of the file and place them into the lines set */
while(reader.hasNext()){
lines.add(reader.next());
} // end of while
reader.close();
} // end of if
else{
/** Throw exception if the file does not exist */
throw new FileNotFoundException("File not found: " + filename);
} // end of else
/** Call calculateCharCountAlpha */
calculateCharCountAlpha();
} // end of constructor
我遇到的問題是在程序的輸出中。 當我打印出來,從「線」設置,我得到的文件名,而所需的行,當我從我的其他方法,打印出的其他設置的項目,它工作正常,但它正在分析文件名,而不是文本在文件中。 我不確定這是爲什麼。
我已經張貼displayCharCountAlpha代碼前一個問題(發現能夠正常工作),所以我將不包括。
displayCharCountAlpha():
public void displayCharCountAlpha(){ // prints out charCountAlpha
System.out.println(charCountAlpha);
}
displayCharCountNumericDescending():
public void displayCharCountNumericDescending() { // prints out charCountNumericDescending
System.out.println(charCountNumericDescending);
}
顯示():
public void display(int numberOfLines){
int count = 0; // control-variable that can be checked throughout iteration
for(String s : lines){
System.out.println(s);
count++;
if(count == numberOfLines-1){ // number of lines insinuates that the loop has the set amount of times
break; // break out of the loop
} // end of if
} // end of for
} // end of Display()
變化FileExaminer'的'第五行到'掃描儀讀取器=新掃描儀(文件);' –
我作出這種變化。我沒有得到任何輸出。它看起來像我正確地閱讀文件的內容?注意:該文件是Edgar Allen Poe的詩,「Raven」。 – Tobymac208
好了,你有沒有顯示'display',代碼'displayCharCountAlpha'和'displayCharCountNumericDescending'所以我需要精神力量,以進一步幫助您。 –