12
\$\begingroup\$

The main objective of this code is that you must accept an input from the user and loop and remove the consonants and vice versa and display the new word.

I know there is a easier way of doing it, but I have no idea how.

String test = "john doe", check;
    for(int ktr = 0; ktr < test.length(); ktr++){
       // System.out.println(test.substring(ktr, ktr+1));
        check = test.substring(ktr, ktr+1);
        if(!"b".equals(check) && !"c".equals(check)){
            if(!"d".equals(check) && !"f".equals(check)){
                if(!"g".equals(check) && !"h".equals(check)){
                    if(!"j".equals(check) && !"k".equals(check)){
                        if(!"l".equals(check) && !"m".equals(check)){
                            if(!"n".equals(check) && !"p".equals(check)){
                                if(!"q".equals(check) && !"r".equals(check)){
                                    if(!"s".equals(check) && !"t".equals(check)){
                                        if(!"v".equals(check) && !"w".equals(check)){
                                            if(!"x".equals(check) && !"y".equals(check)){
                                                if(!"z".equals(check)){
                                                     System.out.print(check);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }   
        }
    }
\$\endgroup\$
0
19
\$\begingroup\$

So it looks like you're just printing out the vowels in your string, right?

System.out.println(answer.replaceAll("[^AaeEiIoOuU]", ""));

Removes the for loop and compacts your code a lot, making it a lot more readable IMO. Also notice how easy it was for me to extend to capital letters.


It would be good to note that this is a replacement for your block of code as it is right now. If you plan on printing the vowels in a variable amount of strings (perhaps input by the user), then you would want to make a method that would do this for you. In this function you would pass in the precompiled regex and the string to print.

I wrote this up really quick in a text editor and didn't compile it, but here is a program that could handle multiple strings better:

class VowelPrinter
{
    static final Pattern p = Pattern.compile("[^AaeEiIoOuU]");

    public static String removePattern(Pattern p, String str)
    {
        return p.matcher(str).replaceAll("");
    }
    public static void main (String[] args)
    {
        int num = 0;

        System.out.print("How many names are you going to save: ");
        Scanner in = new Scanner(System.in);
        num = Integer.parseInt(in.nextLine().trim());

        String names[] = new String[num];
        for (int i = 0; i < names.length; i++)
        {
            System.out.print("Type a name: ");
            names[i] = removePattern(p, in.nextLine());
        }
        System.out.println("Names with consonants removed:");
        for (int i = 0; i < names.length; i++)
        {
            System.out.println(names[i]);
        }
    }
}
\$\endgroup\$
4
  • \$\begingroup\$ Basically yes, I am just printing the vowels of the string, depending on the user's input. I just find my code is insufficient cuz of so many if else statement. Well, just to clarify my goal in my code. The user gives a string for example "Hello" and you just to loop and find delete all consonants and vice versa and display the new word. The code I have given is what I could have think of... \$\endgroup\$ Nov 29 '15 at 18:52
  • \$\begingroup\$ @ILoveYou You should edit that information into your question. Also, is the user only inputting one word, or several? \$\endgroup\$
    – syb0rg
    Nov 29 '15 at 18:53
  • \$\begingroup\$ Sorry for not putting the information to my question. Kinda new to this website so yeah. The user may input one word or several, but since it's a fix string I just used substring. \$\endgroup\$ Nov 29 '15 at 18:55
  • \$\begingroup\$ What about spaces and dots and other stuff? The original code only uses a blacklist, you're using a whitelist here. \$\endgroup\$ Jul 30 '17 at 14:52
18
\$\begingroup\$

Avoid multiple statements per line like this:

String test = "john doe", check;

It's hard to see that there's another variable declaration, check, at the end of that line. This is better:

String test = "john doe";
String check;

However, you didn't need to declare check before the loop. You could declare it inside the loop, and it would be better:

for(int ktr = 0; ktr < test.length(); ktr++){
    String check = test.substring(ktr, ktr+1);

The reason this is better is that check is not used anywhere outside this loop. By declaring it inside, you make it impossible to use it outside, which reduces potential mistakes.

Instead of iterating over the character position indexes and then creating a single-character string in check using test.substring, it would have been better to iterate over the characters, like this:

for (char c : test.toCharArray()) {

This would allow to replace the tedious !"x".equals(check) conditions with simpler 'x' != c. Or even a switch, like this:

switch (c) {
    case 'b':
    case 'c':
    // ... many more cases...
        break;
    default:
        System.out.print(c);
}

Of course, none of this matters much (except for your learning), because @syb0rg is right, this can be greatly simplified using a regex.

A slightly simpler variation over the regex given by @syb0rg is to ignore upper/lower case in the pattern, by inserting (?i) anywhere inside the pattern string:

System.out.println(answer.replaceAll("(?i)[^aeiou]", ""));

However, as @Simon hinted in a comment, this will remove more than just consonants, it will remove everything that is not a vowel. To remove strictly consonants only, you can list them explicitly, instead of the simpler rule of "non-vowels" in the previous example:

System.out.println(answer.replaceAll("(?i)[bcdfghjklmnpqrstvwxyz]", ""));
\$\endgroup\$
2
  • \$\begingroup\$ What about spaces and dots and other stuff? The original code only uses a blacklist, you're using a whitelist with the regex. \$\endgroup\$ Jul 30 '17 at 14:53
  • \$\begingroup\$ @SimonForsberg thanks, good point, updated ;-) \$\endgroup\$
    – janos
    Jul 30 '17 at 16:01
2
\$\begingroup\$

Another solution would put the vowels into an array and just loop the given input String and in each character search in the vowels array.

Just try to avoid regex because it is unreadable.

Regex isn't difficult, the problem is if you don't work with it daily probably in months you will forget what it do.

\$\endgroup\$
1
  • \$\begingroup\$ You don't need to be afraid of simple regular expressions, there's always regex101.com. \$\endgroup\$ Oct 26 '17 at 22:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.