2016-07-05 69 views
-2

我的代碼中有一個問題,我要求查找字符串中字符的出現次數,但我一直有一個Exception錯誤,而且我沒有知道爲什麼?這是我的代碼:查找字符串中出現字符的次數

import java.io.IOException; 
import java.util.*; 
import java.lang.*; 

public class LabOne1 { 

    public static void main(String[] args) throws IOException { 

    Scanner scan = new Scanner(System.in); 

    System.out.print("Enter a string: "); 
    String strUser = scan.next().toLowerCase(); 

    System.out.print("Enter a character: "); 
    char charUser = (char) System.in.read(); 
    Character.toLowerCase(charUser); 

    System.out.print(charUser + "occurs " + count(strUser, charUser) + 
      " times in the string " + strUser); 
    } 

    public static int count(String str, char a){ 

    int counter = 0; 

    for(int i = 0; i <= str.length(); i++){ 
     if (str.charAt(i) == a){ 

      counter++; 
     } 
    } 

    return counter; 
    } 
} 
+1

我們不是一個調試服務。一旦你找到問題代碼,問一個*特定*問題。 – Li357

+1

我們不知道爲什麼你會收到例外。我們也不知道您得到的例外情況,或者您生成的代碼中的哪些位置,或者您輸入的輸入內容,或者您​​未提供給我們的任何其他信息。 – azurefrog

+1

他們的意思是,請包括您詢問的異常的堆棧跟蹤。 – erickson

回答

3

您的字符串索引不正確。有效索引在0之間(包括0和0),並且不包括str.length()你的循環能像這樣工作:

for(int i = 0; i < str.length(); i++) { 
    if (str.charAt(i) == a) counter++; 
} 

或者,你可以做這樣的事情:

int count = Math.toIntExact(str.chars().filter(ch -> ch == a).count()); 
+0

非常感謝你,它的工作,並且確實我的索引超過了字符串的長度。 –

相關問題