1

First of all, excuse me for my bad english. It's not my native language (this is one of my problems, you'll see later why).

I'm making a method in Java and it is proposed to count vowels of a String. The input comes from windows prompt, because i'm compiling and executing using javac and java commands, respectively.

I've written some lines of code to solve the exercise but i can't count vowels which have accent marks. eg. When i try "canción", its output just count 2 vowels.

public static int countVowels(String text){
    int answer = 0;
    String test = "AEIOUaeiou";
    for (int i = 0; i < text.length(); i++)
        for (int j = 0; j < test.length(); j++)
            if (text.charAt(i) == test.charAt(j))   {
                answer++;
                break;
            }
    return answer;
}

public static void form() {
    Scanner in = new Scanner(System.in);
    System.out.println("This program counts the number of vowels.");
    int answer = 0;
    String text = "";
    while (!text.equals("-1"))  {
        System.out.print("Enter a line of text (-1 to exit): ");
        text = in.nextLine();
        answer = Character.countVowels(text);
        System.out.println("Number of vowels: " + answer);
    }
    System.out.println("Closing the program...");
} 

I'm using Scanner as input method.

I tried comparing 2 Strings, 'cause i think using if(text.charAt(i) == 'A') is just boring (Maybe i'm wrong).

Really I don´t know what to do. I've tried using Ascii values (193 = Á), I tried just writing de vowels with accent mark in the test String String test = "AEIOUaeiouÁÉÍÓÚáéíóú";.

Nothing works. I'll be very grateful to the person who can help me.

PS, i'm not allowed to use array.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Possible duplicate of [What's the best way to check if a character is a vowel in Java?](http://stackoverflow.com/questions/26557604/whats-the-best-way-to-check-if-a-character-is-a-vowel-in-java) – Erwin Bolwidt Jul 08 '16 at 02:53
  • I wouldn't call your class `Character` as that name clashes with `java.lang.Character`. In general, don't use a class name that exists in the `java.lang` package, as this leads to a lot of confusion, because it is auto-imported in each java source file. – Erwin Bolwidt Jul 08 '16 at 02:55
  • Thank you for the advice, i'll edit. – José Díaz Rincón Jul 08 '16 at 03:10
  • Hmm interesting. As far as I know, we cannot count the accented vowels unless we include those in an if clause as well. This would mean identifying all the possible accented characters which are vowels and increasing a counter every time we encounter one. – Aditya Gupta Jul 08 '16 at 05:24

1 Answers1

1

The simplest way to count "vowels" is this one-liner:

int vowelCount = str.replaceAll("[^AEIOUaeiouÁÉÍÓÚáéíóú]", "").length();

This find using regex and deletes (replaces with blank) all characters not one of the ones listed (via the negative character class).

Bohemian
  • 412,405
  • 93
  • 575
  • 722