ファイルを取り込んでファイル内の単語数を出力するプログラムを構築しようとしています。すべてが1つの段落全体の下にある場合、それは完全に機能します. ただし、複数の段落がある場合、新しい段落の最初の単語は考慮されません。たとえば、ファイルが "My name is John" の場合、プログラムは "4 words" を出力します。ただし、ファイルが「My Name Is John」で、各単語が新しい段落である場合、プログラムは「1 単語」を出力します。if ステートメントに関する何かに違いないことはわかっていますが、新しい段落の最初の単語を考慮して、新しい段落の前にスペースがあると想定しました。一般的な私のコードは次のとおりです。
import java.io.*;
public class HelloWorld
{
public static void main(String[]args)
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("health.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int word2 =0;
int word3 =0;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
;
int wordLength = strLine.length();
System.out.println(strLine);
for(int i = 0 ; i < wordLength -1 ; i++)
{
Character a = strLine.charAt(i);
Character b= strLine.charAt(i + 1);
**if(a == ' ' && b != '.' &&b != '?' && b != '!' && b != ' ' )**
{
word2++;
//doesnt take into account 1st character of new paragraph
}
}
word3 = word2 + 1;
}
System.out.println("There are " + word3 + " "
+ "words in your file.");
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
if文の複数チームを調整してみましたが、違いはないようです。私がどこを台無しにしているのか誰か知っていますか?
私はかなり新しいユーザーで、数日前に同様の質問をして、ユーザーに要求が多すぎると非難されたので、これで私の質問が少し絞り込めることを願っています. 新しい段落の最初の単語が考慮されていない理由について、私は本当に混乱しています。さらに情報が必要な場合はお知らせください。ありがとう!!