2016-04-17 99 views
3

當我的代碼編譯它給我多元的元音輸出。幾乎就像在它檢查每個字符後給它一個輸出。我如何讓它與我所有的元音和其他元素一起輸出一個輸出。在1輸出?使用字符串方法來查找和計算字符串中的元音?

請幫助...

import java.util.*; 

public class Lowercasevowelcounter { 

    public static void main(String[] args) { 

    int a=0, e=0, x=0; 
    int u=0, o=0, other=0; 

    String text; 
    Scanner sc = new Scanner(System.in); 


    System.out.println("Enter a string of words : "); 
    text = sc.nextLine(); 

    for (int i = 0; i < text.length(); i++){ 
     char c = text.charAt(i); 

     if (c == 'a') a++; 

     else if (c == 'e') 
      e++; 

     else if (c == 'i') 
      x++; 

     else if (c == 'o') 
      o++; 

     else if (c == 'u') 
      u++; 

     else 
      other++; 

     System.out.println("a: " + a + "\n" + 
       "e: " + e + "\n" + 
       "i: " + x + "\n" + 
       "o: " + o + "\n" + 
       "u: " + u + "\n" + 
       "other: " + other); 
    } 
    } 
} 

回答

3

你有內部的中的System.out.println(...)的循環。嘗試將其解壓到for循環之外。

... 
for (int i = 0; i < text.length(); i++){ 
    char c = text.charAt(i); 

    if (c == 'a')a++; 
     else if (c == 'e') e++; 
     else if (c == 'i') x++; 
     else if (c == 'o') o++; 
     else if (c == 'u') u++; 
    else 
    other++; 
} 

System.out.println("a: " + a + "\n" + 
     "e: " + e + "\n" + 
     "i: " + x + "\n" + 
     "o: " + o + "\n" + 
     "u: " + u + "\n" + 
     "other: " + other); 
... 
+0

工作....謝謝...不能相信我沒有看到!....非常感謝! – Savage99