What your code is doing is simply printing what someone else types. You need to add summation logic and alphabet mapping. For this, you can make the following modifications:
1- Create a method that counts the 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 well. The big balcony here is to check if the character has a numerical mapped value and add it to the totalizer. This can be done in many ways, for simplicity you can use 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;
}
Using% w / o%, the numerical value check logic of the character is only the call of the Map
method.
2- Print the sum of the word:
int valorSoma = calcularSomaPalavra(soma, alfabeto);
System.out.println(valorSoma);
Now you're actually printing the sum, 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;
}
One tip is to always get a problem and break it down into resolution steps, so you can solve a bigger problem by solving each step of it, which makes it easier to work out the overall solution.