Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created January 8, 2020 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/501342740c15daea7b63148eeb606d4f to your computer and use it in GitHub Desktop.
Save parzibyte/501342740c15daea7b63148eeb606d4f to your computer and use it in GitHub Desktop.
/*
* Archivo: ContarVocalesJava.java
* Clase: ContarVocalesJava
* Autor: parzibyte
* Fecha: 1/7/20 10:16 PM
* Visita https://parzibyte.me/blog para más tutoriales sobre Java
*/
import java.util.HashMap;
public class ContarVocalesJava {
public static void main(String[] args) {
// La cadena a la que le contaremos las vocales
String cadena = "Mi nombre es Luis Cabrera. Tengo un blog en parzibyte.me/blog y aunque no es mi lenguaje favorito, me gusta Java";
// Crear e inicializar mapa
// Tutorial de mapas: https://parzibyte.me/blog/2020/01/07/hashmap-java-tutorial-ejemplos/
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("a", 0);
hashMap.put("e", 0);
hashMap.put("i", 0);
hashMap.put("o", 0);
hashMap.put("u", 0);
// Recorremos la cadena letra por letra y vemos si es una vocal
for (int x = 0; x < cadena.length(); x++) {
char letraActual = cadena.charAt(x);
if (esVocal(letraActual)) {
// La clave es la vocal en sí, pero en minúscula
String clave = String.valueOf(letraActual).toLowerCase();
// Aumentamos el conteo en esa clave
hashMap.put(clave, hashMap.get(clave) + 1);
}
}
System.out.printf("Resultados para '%s':\n", cadena);
//Imprimir resultados
for (HashMap.Entry<String, Integer> entry : hashMap.entrySet()) {
System.out.printf("Vocal: %s. Conteo: %d\n", entry.getKey(), entry.getValue());
}
}
private static boolean esVocal(char letra) {
return "aeiou".contains(String.valueOf(letra).toLowerCase());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment