我想寫我自己的Java字數統計程序。我知道這可能已經有一種方法,但我想讓它工作。我在第14行出現越界錯誤。我試圖用一個輸入詞來計算它在輸入字符串中出現的次數。所以我循環到stringlength
- wordlength
,但這就是問題所在。超出範圍錯誤與字數
下面是代碼:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
它似乎工作正常。你得到IndexOutOfBoundsException的輸入是什麼? –