2014-09-22 104 views
-4
import java.util.Random; 

public class Test{ 
    public static void main(String[] args){ 
     final Random r = new Random(); 


     String ch = "aeiouycbdfgh"; 
     int len = r.nextInt(10) + 10; 
     StringBuffer sb = new StringBuffer(); 
     for (int i=0; i<len; i++){ 
      sb.append(ch.charAt(r.nextInt(ch.length()))); 
     } 
     System.out.println("String:" + sb); 
     System.out.println("Vowels:"); 
     outputVowels(sb.toString()); 

    } 


    public static void outputVowels(String s){ 

我該如何做一個for循環來輸出每個不同行中的ch字符串的元音?使用For循環打印出元音

編輯:該程序是爲了輸出 一個 ê 我 Ø ü

+1

'對(INT I = 0;我<5; i ++)System.out.println(ch.charAt(i));'? – Seelenvirtuose 2014-09-22 07:45:37

+0

@Seelenvirtuose,他們已經摸索似乎的問題。他們從ch創建一個隨機選擇的新字符串。你可以在代碼中看到他們打算在構建器中顯示元音。 – ChiefTwoPencils 2014-09-22 07:48:32

+1

來自我的投票 - 沒有明顯跡象表明以前的研究或努力。這是一個非常常見的編程任務 - 沒有任何嘗試只是很差。 – 2014-09-22 07:49:46

回答

2

首先制定全球元音集合 - 快速訪問:

Set<Character> vowelSet = new HashSet<>(); 
vowelSet.addAll(Arrays.asList('a', 'e', 'i', 'o', 'u')); 

其次,你可以寫掃描循環像這樣:

String str = "ahjuekjdf"; 

for (int i=0; i<str.length(); i++) { 
    char c = str.charAt(i); 
    if(vowelSet.contains(c)) { 
     System.out.println(c); 
    } 
} 
+0

可能會更加整潔:for(char c:str.toCharArray()){...}。 – 2014-09-22 07:56:44

+0

確實,str.toCharArray是整潔的,但在後面執行不必要的數組拷貝......但我同意 - 在這種情況下,可讀性更重要:) – 2014-09-22 07:59:40

+0

@przemek hertel +1採用數組列表 – deogratias 2014-09-22 08:00:39

0

改變你的循環到

for (int i=0; i<len; i++) { 
    char c = sh.charAt(i); 
    if ((c=='a')||(c=='e')||(c=='i')||(c=='o')||(c=='u')) { 
     sb.append(ch.charAt(r.nextInt(ch.length()))); 
    } 
} 
1

可以直接使用Regex

public class Test { 
    public static void main(String[] args) { 
     String s = "Ankur"; 
     s = s.replaceAll("[^aeiouAEIOU]", ""); 
     System.out.println(s); 
    } 
} 

輸出

Au