2014-10-11 107 views
0

我試圖優化我的Java代碼,所以我嘗試了一些東西。在我的簡短搜索中,我在下面編寫了代碼。這會拋出一個Exception。你能告訴我爲什麼嗎?我不能通過char數組來循環一個字符串嗎?通過字符數組和循環字符循環

public class Input { 

    public static void main(String[] args) { 

     String check = "Dit moet toch gewoon te doen zijn !!"; 
     check = check.toLowerCase(); 

     int[] counter = {0, 0, 0, 0, 0}; 
     char[] vowel = {'a', 'e', 'i', 'o', 'u'}; 

     int total = 0; 
     for (int i = 0; i < check.length(); i++) 
      if (check.charAt(i) == vowel[i]) 
       counter[i]++; 

     for (int t : counter) 
      total += t; 

     System.out.println("Aantal klinkers: \t" + total); 

    } 
} 
+0

按照我的理解唯一的例外是在拋出:'如果(檢查。 charAt(i)==元音[i])' – 2014-10-11 11:03:52

+0

您已將字符串與元音數組的長度混合在一起。 – blackSmith 2014-10-11 11:04:14

+0

「counter」和「vowel」有5個元素,「check」有30個元素。換句話說,你的循環沒有被正確構建。 – Keppil 2014-10-11 11:04:16

回答

3

你的代碼讀取這樣的: 對於每個角色在「檢查」 如果字符在指數中的「檢查」是在「元音」

索引字符這可能不是你要找的內容。你得到的例外是因爲「元音」中只有5個字符,而「檢查」中有很多(我不計數)

現在,我假設你想要做的是實際計數「檢查」中每個元音的數量

在這種情況下,實際上應該使用嵌套for循環。

for (int i = 0; i < check.length(); i++) { 
    for (int v = 0; v < vowel.length; v++) { 
     if (check.charAt(i) == vowel[v]) { 
      counter[v]++; 
      break; 
     } 
    } 
} 
0

您必須具有兩個環路 一爲通過串字符每去和一個循環通過每個元音陣列會像這樣

for (int i = 0; i < check.length(); i++) 
    for (int p = 0; p < vowel.length; p++) 
     if (check.charAt(i) == vowel[p]) 
      counter[p]++; 

享受。

+0

大聲笑我知道對不起jst現在改變,難以在平板電腦 – 2014-10-11 11:15:30

2
for (int i = 0; i < check.length(); i++) 
    if (check.charAt(i) == vowel[i]) 
     counter[i]++; 

此迴路從0check.length();但是你的數組vowel[]有5個元素。所以它會產生數組超出界限的異常。

0

你可以使用正則表達式進行此操作:

Pattern vowels = Pattern.compile("(?i)[aeiou]"); 
String check = "Dit moet toch gewoon te doen zijn !!"; 

Matcher matcher = vowels.matcher(check); 

while(matcher.find()) { 
    System.out.println("found vowel: " + matcher.group()); 
} 

正則表達式的說明:

(?i)使花紋不區分大小寫,[aeiou]字符相匹配。

+0

不錯,我不知道我明白它是如何工作的,但謝謝! – Roy 2014-10-11 12:04:21

+0

只是谷歌正則表達式,如果你想知道更多。使用字符串時非常有用。 – PeterK 2014-10-11 12:28:42

0

還有一對聰明的正則表達式部門,所以你不必讓您的字符串小寫和失去的情況下元音:

if (check.matches("(?i)[^a-z][a-z].*")) 
    System.out.println("Vowels found: " + check.replaceAll("[^a-z]+", ""));