2014-01-25 70 views
0

我想寫我自己的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; 
    } 
} 
+2

它似乎工作正常。你得到IndexOutOfBoundsException的輸入是什麼? –

回答

0

首先,二Scanner s爲沒有必要,你可以做很多的投入與同Scanner對象。

而且,這種if條件

if (match(substring, word) == true) 

可以改寫像

if (math(substring, word)) 

我也建議你使用i++增加循環變量。不是絕對必要的,而是「幾乎」的一種慣例。你可以read more about that here

現在,關於IndexOutOfBoundsException,我測試了代碼,但沒有找到任何輸入樣本來獲取它。

此外,還有一個問題,你在for缺少一個迭代:

for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1' 
    String substring = string.substring(i, i + word.length()); 
    // System.out.println(substring); 
    if (match(substring, word)) { 
     count++; 
    } 
} 

您可以通過將一個打印聲明內循環測試,打印每個子字符串。

+0

謝謝,這固定它。 – slaga

0

我沒有得到一個出界失誤,你能告訴我你正在使用的詞和字符串值是什麼?

我發現了一個程序錯誤。如果單詞等於字符串,它仍然返回計數0.我建議再添加一個迭代並使用regionMatches代替。如果word.length()+ i等於或大於string.length(),則RegionMatches會使匹配方法過時並返回false,從而避免出現界限問題。

正如你所看到的,我也將計算轉移到了單獨的方法,這將使你的代碼更具可讀性和可測試性。

正如Christian指出的那樣;你確實只需要一個Scanner對象。我已經修改了下面的代碼來反映它。

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    System.out.print("Enter word : "); 
    String word = sc.nextLine(); 
    System.out.print("Enter string: "); 
    String string = sc.nextLine(); 
    int count = calculateWordCount(word, string); 
    System.out.println("There are " + count + " repetitions of the word " + word); 
} 

private static int calculateWordCount(String word, String string) { 
    int count = 0; 
    for (int i = 0; i < string.length() - word.length() + 1; i++) { 
     if (word.regionMatches(0, string, i, word.length())) { 
      count++; 
     } 
    } 
    return count; 
} 
+0

謝謝,我從中學到了。 – slaga