2014-09-22 161 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