このファイルから(正しく)テキストを読んでいるのか不思議です。Java - このファイルからテキストを正しく読み込んでいますか?
目的:ファイルからテキストを読み込んで、 "lines"という名前のセットに配置します(追加された順序で要素がソートされるため、セットはLinkedHashSetです)。ここ
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<>();
からコードである。ここで
は、main()関数(輸入省略)からのコードでありますここで参照されている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」の5行目を「Scanner reader = new Scanner(file);」に変更します。 –
この変更を行いました。私は出力のために何も得ていない。ファイルの内容を正しく読み込んでいるように見えますか?注:このファイルはEdgar Allen Poeの詩「Raven」です。 – Tobymac208
さて、あなたは 'display'、' displayCharCountAlpha'、 'displayCharCountNumericDescending'のコードを表示していませんので、私はあなたを助ける精神力が必要です。 –