-6
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){

How do i make a for loop that will output the vowels of the ch string each in a different line?

edit: the program is meant to output a e i o u

totallynotgroot
  • 59
  • 2
  • 3
  • 13
  • 1
    `for(int i = 0; i < 5; i++) System.out.println(ch.charAt(i));` ? – Seelenvirtuose Sep 22 '14 at 07:45
  • @Seelenvirtuose, they've fumbled the question it seems. They create a new string of randomly selected chars from ch. You can see in the code they intend to show the vowels in the builder. – ChiefTwoPencils Sep 22 '14 at 07:48
  • 2
    Down-vote from me - no apparent sign of prior research or effort. This is a very common programming assignment - making no attempt is just poor. – Duncan Jones Sep 22 '14 at 07:49
  • @ChiefTwoPencils This is why I put a question mark at my comment. In fact, the question should be edited because it is very unclear. – Seelenvirtuose Sep 22 '14 at 07:50
  • Possibly duplicate of http://stackoverflow.com/questions/19160921/how-do-i-check-if-a-char-is-a-vowel – Manu Sep 22 '14 at 07:54
  • 1
    Question after the edit: Why do you have so much code dealing with randoms although the "program is meant to [simply] output a e i o u"? This is a poor question deserving a downvote. – Seelenvirtuose Sep 22 '14 at 07:57

4 Answers4

2

First prepare global vowel set - for fast access:

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

Second, you can write scanning loop like this:

String str = "ahjuekjdf";

for (int i=0; i<str.length(); i++) {
    char c = str.charAt(i);
    if(vowelSet.contains(c)) {
        System.out.println(c);
    }
}
przemek hertel
  • 3,924
  • 1
  • 19
  • 27
1

You can directly use Regex

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

Output

Au
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
0

change your loop to

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())));
    }
}
Pino
  • 7,468
  • 6
  • 50
  • 69
deogratias
  • 472
  • 2
  • 8
  • 23
0
 for(char v : vowel){
    if(ch == v){
        cout <<ch<<" is vowel";
        break;
    }
    else{
        cout <<ch<<" is consonant";
        break;
    }
}