Calvin.Xie Calvin.Xie - 23 days ago 6
Java Question

how to count the number of letters in an array java

I have an assignment about how to count the number of letters in an array.
Here is my code:

import java.util.Scanner;

public class task1 {

public static void main(String[] args) {
// TODO Auto-generated method stub




//Create a scanner object
Scanner input = new Scanner(System.in);

//Prompt user's input
System.out.println("Enter strings (use a space to separate them; hit enter to finish) : ");

String str = input.nextLine();

// use split to divide the string into different words cutting by " "
String [] wordsArray = str.trim().split(" ");

System.out.println("The length of string is " + wordsArray.length);




for(int i = 0 ; i < wordsArray.length; i++){


char [] eachLetterinArray = wordsArray[i].toCharArray();


for(int j = 0,count = 0 ; j < eachLetterinArray.length; j++){

if( (eachLetterinArray[j]+'a'-97 >=65 && eachLetterinArray[j]+'a'-97 <=90 )
|| (eachLetterinArray[j]+'a'-97 >=97 && eachLetterinArray[j]+'a'-97 <=122 ) ){

count++;

}

System.out.print(count);
}





}
}


if I enter "end tr"
the output is "12312"
but what I want is "3 and 2 "

I have tried a lot and still have nothing to do about this...
can you help me?

Answer

You want to print count per word, but you are printing for each character. Just print the count variable outside of the inner loop.

for (int i = 0; i < wordsArray.length; i++) {
    char[] eachLetterinArray = wordsArray[i].toCharArray();
    int count = 0;
    for (int j = 0; j < eachLetterinArray.length; j++) {
        if ((eachLetterinArray[j] + 'a' - 97 >= 65 && eachLetterinArray[j] + 'a' - 97 <= 90)
                || (eachLetterinArray[j] + 'a' - 97 >= 97 && eachLetterinArray[j] + 'a' - 97 <= 122)) {

            count++;
        }                
    }
    System.out.println(count);
}

Improvement:

Instead of the little bit complex condition, you can do this way also:

if (Character.isLetter(eachLetterinArray[j])) {
    count++;
}