Rick
Rick

Reputation: 85

Print vowels from a word in Java

I am a beginner at java and I am doing this course an needed some help with this. Basically, a user will input a string and then the program will print out only the vowels on one line.

import java.util.Scanner; 

class Main {
  public static void main(String[] args) {
    Scanner inp = new Scanner(System.in);
    System.out.print("In:");
    String word = inp.nextLine();
    //write your code below
    for(int whatsat = 0; whatsat < word.length(); whatsat++){
      if (word.charAt(whatsat).equals("a")){  //how to declare mutiple letters?
        System.out.print(word.charAt(whatsat));
      }

  }
}
}

Upvotes: 4

Views: 10704

Answers (5)

Zephyr
Zephyr

Reputation: 10253

A simple way to do this (intentionally avoiding complex regex options) would be to use the String.indexOf() method within your loop.

In the example below, we basically check if "AEIOUaeiou" contains the char that we're pulling from the user's input. If so, we extract it:

public static void main(String[] args) {
    Scanner inp = new Scanner(System.in);
    System.out.print("In:");
    String word = inp.nextLine();

    //write your code below

    // This will hold any matching vowels we find
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < word.length(); i++) {

        // Check if our list of vowels contains the current char. If the current char exists in the String of vowels, it will have an index of 0 or greater.
        if ("AEIOUaeiou".indexOf(word.charAt(i)) > -1) {

            // If so, add it to our StringBuilder
            sb.append(word.charAt(i));
        }
    }

    // Finally, print the result
    System.out.println(sb.toString());

}

The Result:

With test input of "This is my test input. Did it work?" the output is: iieiuiio

Upvotes: 1

nabster
nabster

Reputation: 1675

I prefer to use Hashmap as lookup is O(1)

    public class PrintVowelsInWord {

    public static Map<Character, Character> vowels;

    public static void main(String[] args) {
        loadMap();
        // for simplicity sake I am not using Scanner code here
        getVowels("wewillrockyou");
    }

    public static void loadMap() {
        if (vowels == null) {
            vowels = new HashMap<>();
            vowels.put('a', 'a');
            vowels.put('e', 'e');
            vowels.put('i', 'i');
            vowels.put('o', 'o');
            vowels.put('u', 'u');
        }
    }

    public static void getVowels(String input) {
        for (Character letter : input.toCharArray()) {
            if (vowels.containsKey(letter)) {
                System.out.print(letter);
            }
        }
    }
}

Upvotes: 0

vs97
vs97

Reputation: 5859

I am really surprised nobody has suggested using Enums... Cleanest way and simplest way, in my opinion.

Simply define an Enum with all the vowels, go through the String and compare each character to the values inside of Enum, ignoring the case - note the cast of char into String. If it is present in the Enum, print it out.

public class VowelFind  {

    enum Vowels {
        A, E, I, O, U
    }

    public static void main(String[] args) {
        Scanner inp = new Scanner(System.in);
        System.out.print("In:");
        String word = inp.nextLine();

        for (int i = 0; i < word.length(); i++) { //loop through word
            for (Vowels v : Vowels.values()) { //loop through Enum values
                if((word.charAt(i)+"").equalsIgnoreCase(v.name())) { //compare character to Enum value, ignoring case
                    System.out.print(word.charAt(i));
                }
            }
        }
    }
}

Input: Hello World
Output: eoo

Upvotes: 0

broAhmed
broAhmed

Reputation: 192

So there's two issues here:

  1. Characters are compared differently from Strings.
  2. Checking for multiple characters.

To compare characters, do something like:

if (word.charAt(whatsat) == 'a') {
    ...
}

Note the single quotes! 'a' not "a"!

If you're asking "why are comparisons for strings and characters different?", that's a good question. I actually don't know the reason, so we should both research it. Moving on.

To check for multiple characters:

for(int whatsat = 0; whatsat < word.length(); whatsat++){
    if (word.charAt(whatsat) == 'a' || word.charAt(whatsat) == 'e' || word.charAt(whatsat) == 'i'){
        System.out.print(word.charAt(whatsat));
    }
  }

Note that if you're input has capital letters, you'll need to either:

  • Convert your input to lowercase so you can just check for lowercase letters, or
  • Explicitly check for capital letters in your if statement, e.g
if (...word.charAt(whatsat) == 'A' ...)

Longterm, you'll want to research regular expressions like a Adrian suggested in the comments. It may be complicated for a beginning student, but if you're interested you should look into it.

Hope this helps.

Upvotes: 0

VietHTran
VietHTran

Reputation: 2318

I agree with @Logan. You don't use equals() to compare primitive type values (int, char, boolean, etc.), just use simple == expression.

import java.util.Scanner; 

class Main {
  public static void main(String[] args) {
    Scanner inp = new Scanner(System.in);
    System.out.print("In:");
    String word = inp.nextLine();
    //write your code below
    for(int whatsat = 0; whatsat < word.length(); whatsat++){
      char c = Character.toLowerCase(word.charAt(whatsat));
      if (c == 'a' || c == 'e'|| c == 'i' || c == 'o' || c == 'u'){
        System.out.print(word.charAt(whatsat));
      }

  }
}
}

Upvotes: 1

Related Questions