Scheids
Scheids

Reputation: 121

How do you remove vowels from a word and print it?

I'm trying to write a program that asks somebody to input a word and then the program removes any vowels in the word and prints the remaining consonant. This is what I have so far:

package r7;

import java.util.Scanner;

public class Disemvowel {
    public static void main(String[] args) {
        Scanner stdin = new Scanner(System.in);
        System.out.println("Please enter a word");
        String word = stdin.next();
        String disemvowlmentWord = "";
        int len = word.length();

        for (int i=0; i<len; i++) {
            char c = word.charAt(i);
            if (c != 'a' | c != 'e' | c != 'i' | c != 'o' | c != 'u')
                disemvowlmentWord = disemvowlmentWord + c;
        }
        System.out.println(disemvowlmentWord);
    }
}

When I run it it just reprints whatever word I enter.

Upvotes: 4

Views: 918

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201439

You used a bitwise or (but every vowel isn't any other vowel), I think you wanted a logical and. This

if (c != 'a' | c != 'e' | c != 'i' | c != 'o' | c != 'u')

should be something like

if (c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u')

You could also use a for-each loop and I would prefer a StringBuilder over creating multiple immutable String(s). Something like,

StringBuilder sb = new StringBuilder();
for (char c : word.toCharArray()) {
    if (c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u') {
        sb.append(c);
    }
}
System.out.println(sb);

Finally, the above test(s) could also be expressed (because of De Morgan's laws) like

if (!(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'))

or you could use a regular expression to replace vowels with an empty String. Something like,

System.out.println(word.replaceAll("[a|e|i|o|u]", ""));

Upvotes: 7

vvs
vvs

Reputation: 1076

You are using the wrong operator. Use && instead of |

Upvotes: -3

Related Questions