How can I make an arrangement like this

1
  • Ask for a name from the keyboard
  • Decompose the letters of the name in an array.
  • Calculate the weight of each letter depending on the position in the alphabet.
  • Add all the weights of each letter of the name and print on the screen only the final result of the sum.
  • THIS IS WHAT I WEAR

    package com.hn.programacion;
    public class Arreglotexto_abecedario {
      public static void main(String[] args) { 
              // TODO Auto-generated method stub String texto= "m"; String [] arregloAbecedario = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x","y", "z"}; System.out.println("Texto de String en la posicion 19= " + arregloAbecedario [19]); 
    for (int indice = 0; indice < arregloAbecedario.length; indice ++){ 
    String elemento = arregloAbecedario [indice];
    
        
    asked by Key_Mar. 27.11.2018 в 03:22
    source

    2 answers

    1

    Assuming that the characters you are going to use are all lowercase, you can convert characters to their ASCII value in the following way

    int asciiValue = (int) character;
    

    The "a" (Minuscule) has an ASCII value of 97. To get your weight you can do

    int charWeight = asciiValue - 96;
    

    I think that with that you can already solve the problem.

    EDIT: This is assuming you change the array from type String (Unnecessary) to type Char.

        
    answered by 27.11.2018 в 03:43
    0

    Greetings, here is a solution. Modify it or optimize it according to your requirements.

    public void algoritmo(){
         Scanner scanner = new Scanner(System.in);
         String entrada = scanner.next();
         System.out.println("Entrada: "+entrada);
    
         scanner.close();
    
         char letras[] = entrada.toCharArray();
         int total = 0;
    
         for(char caracter : letras){
            System.out.println("letra: "+caracter+" valor:"+Integer.valueOf(caracter)); 
            total += caracter;
         }
    
         System.out.println("total: "+total);
    
    }
    
        
    answered by 27.11.2018 в 16:13