Put a number to a string of java characters

0

I am trying to make a program that assigns to each letter of the alphabet a number, all correlative, that is to say = 1, b = 2, c = 3 ... always in lowercase letters and without the ñ. For abcd the output would be 10, or for adef output 16. The code I have is:

import java.util.Scanner;

public class palabras {
public static void main(String args[]) {
    Scanner teclado = new Scanner(System.in);

    System.out.println("Escriba una cadena.");
    String x = teclado.nextLine();
    int s = x.length();
    int f = 0;
    char t;
    for (int i = 1; i < s; i++) {
        t = x.charAt(i);
        for (char a = 'a'; a <= t; a++) {

        }
        f = f+i;

    }
    System.out.println(f);

  }
} 

I know what I have wrong is the for, that if I put af , I get 3, when I would have to leave 7.

    
asked by Fernando 24.01.2017 в 10:14
source

1 answer

2

You can help yourself with the code ASCII :

    int suma = 0;
    String cadena = "abcd";
    for (int i=0; i<cadena.length(); i++){
      if ((int)cadena.charAt(i) != 164){
        suma += (int) cadena.charAt(i) - 96;
      }
    }
    System.out.println(suma);

By passing a char to int , Java converts it into its ASCII code. 164 is the character ñ To check that you only enter a character from a to z you could change the check line of ñ by:

if ((int)cadena.charAt(i) >= 97 && (int)cadena.charAt(i) <= 122)

Here is the table ASCII

    
answered by 24.01.2017 / 10:24
source