What your code is doing is simply printing what someone types. You need to add the sum logic and mapping of the alphabet. For this, you can make the following modifications:
1- Create a method that accounts for sums:
private static int calcularSomaPalavra(String palavra, Map<Character, Integer> alfabeto) {
int valorSoma = 0;
for (char caractere : palavra.toCharArray()) {
if (isCaractereEncontrado(alfabeto, caractere))
valorSoma += getValorCaractere(alfabeto, caractere);
}
return valorSoma;
}
What was done was to create a method that given a word gets the sum of the characters of the word, simple as that. The big thing here is to check if the character has a numerical value mapped and add it to the totalizer. This can be done in many ways, for simplicity you can use a Map
:
// Declaração do map de letras do alfabeto.
Map<Character, Integer> alfabeto = new HashMap<Character, Integer>();
//Mapeamento dos valores de cada letra do alfabeto
alfabeto.put('a', 1);
alfabeto.put('b', 2);
...
alfabeto.put('z', 26);
private static Integer getValorCaractere(Map<Character, Integer> alfabeto, char caractere) {
return alfabeto.get(caractere);
}
private static boolean isCaractereEncontrado(Map<Character, Integer> alfabeto, char caractere) {
return getValorCaractere(alfabeto, caractere) != null;
}
With the use of a Map
, the numerical value of the character checking logic is only the method call get
.
2- Print the sum of the word:
int valorSoma = calcularSomaPalavra(soma, alfabeto);
System.out.println(valorSoma);
Now you are actually printing the sum, and not just what the user types. Putting it all together, we would have:
public static void main(String[] args) {
Map<Character, Integer> alfabeto = new HashMap<Character, Integer>();
Scanner on = new Scanner(System.in);
System.out.println("Digite a palavra: ");
String soma;
soma = on.nextLine();
alfabeto.put('a', 1);
alfabeto.put('b', 2);
...
alfabeto.put('z', 26);
int valorSoma = calcularSomaPalavra(soma, alfabeto);
System.out.println(valorSoma);
}
private static int calcularSomaPalavra(String palavra, Map<Character, Integer> alfabeto) {
int valorSoma = 0;
for (char caractere : palavra.toCharArray()) {
if (isCaractereEncontrado(alfabeto, caractere))
valorSoma += getValorCaractere(alfabeto, caractere);
}
return valorSoma;
}
private static Integer getValorCaractere(Map<Character, Integer> alfabeto, char caractere) {
return alfabeto.get(caractere);
}
private static boolean isCaractereEncontrado(Map<Character, Integer> alfabeto, char caractere) {
return getValorCaractere(alfabeto, caractere) != null;
}
A tip is to always take a problem and divide it into steps of resolution, so you can solve a bigger problem by solving every step of it, which facilitates the elaboration of the global solution.
Hello @Giuliana Bezerra Thank you so much!!!! Very good your explanation!!!! Really very much show!!! You are Awesome!!!!
– Rafaelzinho