テキストファイルの単語数をカウントするプログラムですが、2文字以上の単語のみをカウントしています。以前はうまくいきましたが、突然エラーが発生しました。スレッド "main"の例外java.lang.StringIndexOutOfBoundsException:文字列インデックスが範囲外です:269
スレッド "main"の例外java.lang.StringIndexOutOfBoundsException:文字列インデックスが範囲外です:269?
誰かが助けてくれますか?
import java.io.*;
class count_words {
public static int countWords(String str)
{
int count = 1, num_of_letters = 0, final_count=1;
for (int i=0;i<=str.length()-1;i++)
{
if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
{
if(num_of_letters <= 2)
{
count --;
}
System.out.println("count is " + num_of_letters);
num_of_letters = 0;
count++;
}
else if(str.charAt(i) == ',')
{
num_of_letters --;
}
else
{
num_of_letters++;
}
}
return count;
}
public static void main(String[] args){
//name of file to open
String fileName = "/Users/Chris/Desktop/comp 1 McPhee.txt";
//reference one line at a time
String line = null;
int num;
try
{
//Filereader reads text file in the default encoding.
FileReader filereader = new FileReader(fileName);
BufferedReader bufferedreader = new BufferedReader(filereader);
while ((line = bufferedreader.readLine()) != null)
{
num = countWords(line);
System.out.println(num);
}
}
//Always close file
catch(FileNotFoundException ex)
{
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex)
{
System.out.println("Error reading file '" + fileName + "'");
}
}
}
ようこそスタックオーバーフロー!デバッガの使い方を学ぶ必要があるようです。 [補完的なデバッグ手法](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)にご協力ください。その後も問題が残っている場合は、問題を示す[最小限の、完全で実証可能な例](http://stackoverflow.com/help/mcve)に戻ってください。 –
'i 'が最後の反復の最後のインデックスであるため、' charAt(i + 1) 'は例外をスローしています。 – Gendarme