findOccurrences()
と呼ばれる単一のString
引数を取ると呼ばれる静的メソッドを作成しようとしていますsubString
。まず、このメソッドは.txt
、オブジェクトの作成に使用される拡張子を持つファイルのパス名の入力をユーザーに求める必要がありFile
ます。次に、メソッドはそのファイルでストリームを開く必要があります。続いて、メソッドはストリームから一度に1行ずつ読み取る必要があり、各行について、メソッドはsubString
その行の文字列引数の出現回数を標準出力に出力する必要があります。
メソッドからの出力例は次のようになります。
The substring "FRED" occurs 2 times in line 1
The substring "FRED" occurs 1 times in line 2
The substring "FRED" occurs 4 times in line 3
The substring "FRED" occurs 0 times in line 4
このメソッドは、while
ループが終了したときに、ファイル内のすべての行が読み取られていることを確認する必要があります。ファイルの現在の行を保持する文字列は大文字に変換する必要があります。別のループ内で、メソッドは、引数(大文字に変換)が現在の行の部分文字列として出現する回数を判別する必要があります。したがって、たとえば、現在の行に文字列「BRITAIN POSSESSES TALENT」が含まれている場合、サブ文字列「SSES」を検索すると2回出現するはずです。
今、私はそれにベストショットを与え、必要なメソッドのために以下のコードを開発しました。しかし残念ながら、私がそれをコンパイルするたびに、コンパイラはエラーをスローします:foreach not applicable to expression type
そしてそれは私が立ち往生しているところです!だから私はあなたたちが私が間違っているところを見つけてくれるかどうか疑問に思っていました。
以下は私が開発したコード全体です。
public static void countOccurrences (String subString)
{
OUDialog.alert("Please choose a file to search");
String pathname = OUFileChooser.getFilename();
File aFile = new File(pathname);
BufferedReader bufferedFileReader = null;
int numOfOccurrencesInLine;
int lineNumber = 0;
int lineIndex;
subString = subString.toUpperCase();
String currentLine;
try
{
bufferedFileReader = new BufferedReader(new FileReader(aFile));
currentLine = bufferedFileReader.readLine();
while (currentLine != null)
{
currentLine = bufferedFileReader.readLine();
currentLine.toUpperCase();
lineIndex = currentLine.indexOf(subString, lineNumber);
subString = currentLine.substring(lineIndex);
numOfOccurrencesInLine = 0;
for (int eachOccurrence : currentLine)
{
numOfOccurrencesInLine = numOfOccurrencesInLine + eachOccurrence;
System.out.println("The substring " + subString + "occurs 2 times in line " + lineNumber);
}
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedFileReader.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
}
君たちありがとう。