Determine how many vowels a chain has in java [closed]

1

Implement, using the String class, an application that counts the number of vowels in a text. The algorithm that I have designed is the following:

However, when I try to code the algorithm, everything goes fine until I try to buy with the property ".charAt" the character with "a" ... Since I get the following error:

Is there a more optimal way? or How can I correct my error in order to continue coding my algorithm correctly?

Please remember that this is sequential programming

    
asked by Gabriel Hernández 10.02.2018 в 09:42
source

2 answers

2

First, your compilation error is because you are trying to compare two different types. The charAt(x) function returns a char, normally represented as 'a' , with single quotes. When you try to compare what you do against a String when using the double quotes "a" . All you have to do is change them to make it work.

Regarding efficiency, the only thing I would say is that instead of doing many nested if you use the switch-case structure, which is visually better and makes the checks behind the most efficient and fastest way.

Here is an example of how I would do that part:

String cadena = "Esto es una cadena para contar las vocales";
int a = 0, e = 0, i = 0, o = 0, u = 0;

for (int x = 0; x < cadena.length(); x++) {
    char actual = cadena.toLowerCase().charAt(x);

    switch (actual) {
        case 'a':
            a++;
            break;
        case 'e':
            e++;
            break;
        case 'i':
            i++;
            break;
        case 'o':
            o++;
            break;
        case 'u':
            u++;
            break;
        default:
            break;
    }
}

System.out.println("Total de vocales: " + (a+e+i+o+u));

System.out.println("Cantidad de a: " + a);
System.out.println("Cantidad de e: " + e);
System.out.println("Cantidad de i: " + i);
System.out.println("Cantidad de o: " + o);
System.out.println("Cantidad de u: " + u);

EDITED: I have added a lowercase conversion to check all the vowels regardless of how they are written

    
answered by 10.02.2018 / 11:07
source
1

There are several ways in which you can count all the vowels of a string. But first we should determine what kind of vowels the text could have. For example, if you should handle accented vowels or not, and what types of accents, in Spanish, in French, in Polish ... According to that, you would have to include in the evaluation the possibility for those vowels.

Here I show you several possible ways to do it for a general count of vowels.

If you also want to count each vowel separately, see part II of the answer.

VIEW FULL DEMO ON REXTESTER

I. Voice count in general

Form 1: with regular expressions

This sentence will find all the Castilian vowels, uppercase or lowercase, within a string:

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

We put it in a method, and we test it:

Method contarVocales :

public static int contarVocales(String s){
    int totalVocales = s.replaceAll("[^AEIOUaeiouÁÉÍÓÚáéíóú]","").length();
    return totalVocales;
}

Test:

    String helloWorld="Hello world áéíóÚ";
    totalVocales=contarVocales(helloWorld);
    System.out.println(totalVocales);

Output:

8

Form 2: With a cycle for

Here I have not included the possible vowels in Spanish (accented), but they could be included.

public static int contarVocalesFor(String s){
    int totalVocales = 0;

    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if ((c == 'A') || (c == 'a') || (c == 'E') || (c == 'e') || (c == 'I') || (c == 'i')
      || (c == 'O') || (c == 'o') || (c == 'U') || (c == 'u'))
        totalVocales++;
    }
    return totalVocales;
}

Test:

String loremIpsum=
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua."+ 
    "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. "+
    "Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. "+
    "Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; 

totalVocales=contarVocalesFor(loremIpsum);
System.out.println(totalVocales);  

Output:

162

II. General and partial count

We will adapt the method so that it returns us a HashMap with how many vowels there are of each one and a general count.

public static HashMap<String,Integer> contarVocalesMap(String s){
      HashMap<String,Integer> mapTotal=new HashMap<String,Integer>();  

    int totalVocales = s.replaceAll("[^AEIOUaeiouÁÉÍÓÚáéíóú]","").length();
    int totalA = s.replaceAll("[^AaÁá]","").length();
    int totalE = s.replaceAll("[^EeÉé]","").length();
    int totalI = s.replaceAll("[^IiÍí]","").length();
    int totalO = s.replaceAll("[^OoÓó]","").length();
    int totalU = s.replaceAll("[^UuÚú]","").length();
    mapTotal.put("a",totalA);
    mapTotal.put("e",totalE);
    mapTotal.put("i",totalI);
    mapTotal.put("o",totalO);
    mapTotal.put("u",totalU);
    mapTotal.put("all",totalVocales);
    return mapTotal;
}

We tried the method:

    HashMap<String,Integer> mapTotalVocales=contarVocalesMap(loremIpsum);
    System.out.println(mapTotalVocales);  

Output:

You will have a map like this, with general information and by vowels, it would be a matter of reading it:

{all=162, a=28, e=38, u=29, i=42, o=25}

NOTES:

  • The methods can still be improved, by making them nullsafe .
  • We could even think of a Clase with a much broader scope, having several methods such as: getTotal() for all vowels, getOne() for a given vowel, getOpen() to get only the open vowels. .. Get only the vowels in capital letters, with accents, without accents ... and everything we want with the vowels. :)
  • answered by 10.02.2018 в 11:18