Reputation: 121
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
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