2017-08-07 63 views
0

這是程序誰能幫助我 起初我給字符串第一部分工作正常發現的元音字符串,並將其打印刪除重複的元音字母在一個字符串

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    String a = "History can also refer to the academic discipline "; 
    int count = 0; 

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

     if (a.charAt(i) == 'a' || a.charAt(i) == 'e' || a.charAt(i) == 'i' || a.charAt(i) == 'u' 
       || a.charAt(i) == 'u') { 
      System.out.println("The sentence have vowels:" + a.charAt(i)); 
      count++;//counting the number of vowels 
     } 
     if (a.charAt(i+1) == 'a' || a.charAt(i+1) == 'e' || a.charAt(i+1) == 'i' || a.charAt(i+1) == 'u' 
       || a.charAt(i+1) == 'u') {i++;}//finding reoccurring vowels 
    } 
    System.out.println("number of vowels:" + count); 
} 

}

在第二部分我嘗試跳過重現的元音,但它不工作

+2

*** a.charAt第(i + 1)***,這將爆炸n的for循環 –

+0

最後一次迭代你正在檢查'你'2次和'0'零次 –

+0

我的壞我輸入「u」而不是「o」,但仍然我無法消除反覆出現的元音,所以我應該怎麼做才能糾正它 –

回答

0

你需要做一些改動:

  • 運行循環,直到a.length() - 1因爲你已經爲i+1 ST字符循環
  • 內檢查復位計數,如果第二if條件不滿足。

如:

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    String a = "History can also refer to the academic discipline "; 
    int count = 0; 

    for (int i = 0; i < a.length() - 1; i++) { 

     if (a.charAt(i) == 'a' || a.charAt(i) == 'e' || a.charAt(i) == 'i' || a.charAt(i) == 'u' 
       || a.charAt(i) == 'u') { 
      System.out.println("The sentence have vowels:" + a.charAt(i)); 
      count++;//counting the number of vowels 
     } 
     //finding reoccurring vowels 
     if (a.charAt(i+1) == 'a' || a.charAt(i+1) == 'e' || a.charAt(i+1) == 'i' || a.charAt(i+1) == 'u' 
       || a.charAt(i+1) == 'u') { 
      i++; 
     } else{ 
      count = 0; 
     } 
    } 
    System.out.println("number of vowels:" + count); 
} 
+0

我試過,輸出是這個,但我只想igno再重複元音 (這句話有元音:一 的句子有元音:一 的句子有元音:一 的句子有元音:一 的句子有元音:電子 號元音:0) –

+0

都不行如果最後一個字符是它自己的元音。 – jr593

+0

@MuthuAkilan你不想只計算連續的元音嗎?您可以刪除sysout以擺脫控制檯中的這些語句。 –

0

這個怎麼樣

public static void main(String[] args) { 
    String a = "History can also refer to the academic discipline "; 
    int count = 0; 

    boolean lastWasVowel = false; 

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

     if (a.charAt(i) == 'a' || a.charAt(i) == 'e' || a.charAt(i) == 'i' || a.charAt(i) == 'o' 
       || a.charAt(i) == 'u') { 
      if(!lastWasVowel) { 
       count++; 
      } 
      lastWasVowel = true; 
     } else { 
      lastWasVowel = false; 
     } 
    } 
    System.out.println("number of vowels:" + count); 
} 
+0

這句話有元音:我 的句子有元音:一 的句子有元音:一 的句子有元音:○ 的句子有元音:電子 的句子有元音: Ë 這句話有元音:○ 的句子有元音:電子 的句子有元音:一 的句子有元音:一 的句子有元音:電子 的句子有元音:我 的句子有元音:我 該句有元音:i 該句有元音:i 該句有元音:e 元音數量:16 –

+0

它沒有忽略重複的元音字 –