How to read word by word from an Array? [duplicate]


What I'm looking to do is a counter that adds the value of each word in its ASCI code. For example: Hello (H = 45, or = 56, l = -45, a = 23. Total Value = 79).

This is the code of my Accountant:

public class Accountant {

public static final char espacio = ' ';
char[] pal; //Definim l'array paraula
Paraula p = new Paraula();

public int ContarPes() {
    String S; //Creamos el String para leer desde teclado
    S = new LT().llegirLinia(); //Leemos todo el string
    pal = S.toCharArray(); //Pasamos el String S a Array
    int PesPal = 0; //Ponemos el contador a 0 , el cual dice qué pesa cada palabra

    for (int i = 0; i < pal.length; i++) {
        PesPal = PesPal + pal[i];
    return PesPal;


My problem lies in knowing when you have already read a word, how can you move on to the next one. And at the end I printed the sum of each word per screen.

EDIT: I can only use the String for input or output.

asked by Pedro 14.12.2018 в 16:47

1 answer


In the same class where you have your main, you create a method to use it later:


 public void pesoTexto(String texto){
    char [] letras = texto.toCharArray();
    int total = 0;

    for(char elemento : letras){
        total += elemento;

    System.out.println("Analisis: "+texto+" = peso:"+total);

Then the instances to use it.

  public static void main(String[] args) {
    Respuestas res = new Respuestas();

    String[] palabras = new String[]{"carro","avion","hielo"};
    for(String texto : palabras) res.pesoTexto(texto);
answered by 15.12.2018 в 02:50