user8991131
user8991131

Reputation:

Print out the total number of letters - Java

I want to print out the total number of letters (not including whitespace characters) of all the Latin names in the data file. Duplicate letters must be counted. This is what I have done so far:

List<Person> peopleFile = new ArrayList<>();
int numberOfLetters = 0;

try {
    BufferedReader br = new BufferedReader(new FileReader("people_data.txt"));
    String fileRead = br.readLine();
    while (fileRead != null) {
        String[] tokenSize = fileRead.split(":");
        String commonName = tokenSize[0];
        String latinName = tokenSize[1];
        Person personObj = new Person(commonName, latinName);
        peopleFile.add(personObj);
        fileRead = br.readLine();
        // Iterating each word
        for (String s: tokenSize) {
            // Updating the numberOfLetters
           numberOfLetters += s.length();
        }
    }
    br.close();
}
catch (FileNotFoundException e) {
    System.out.println("file not found");
}
catch (IOException ex) {             
    System.out.println("An error has occured: " + ex.getMessage());
}

System.out.print("Total number of letters in all Latin names = ");
System.out.println(numberOfLetters);

The problem is that it prints out all number of letters in the file, I just want it to print out the number of characters in the Latin names.

The text file:

David Lee:Cephaloscyllium ventriosum
Max Steel:Galeocerdo cuvier
Jimmy Park:Sphyrna mokarren

Upvotes: 0

Views: 550

Answers (2)

Shafin Mahmud
Shafin Mahmud

Reputation: 4071

What you are doing wrong is you are counting all the names despite you tokenize them. You can use this method to count letters of any String or Sentence.

public static int countLetter(String name) {
    int count = 0;

    if(name != null && !name.isEmpty()) {
        /* This regular expression is splitting String at the
         * sequence of Non-alphabetic characters. Hence actually
         * splitting the Name into group of words */
        String[] tokens = name.split("[^a-zA-Z]+");
        for(String token : tokens) {
            count += token.length();
        }
    }

    return count;
}

And replace these lines

        /* Note: here you are iterating all your Names from each line */
        for (String s: tokenSize) {
            // Updating the numberOfLetters
           numberOfLetters += s.length();
        }

with this

numberOfLetters += countLetter(latinName);

Does it make sense ? I hope you found your problem.

NB: you can experiment with this regex here

Upvotes: 0

Mustapha Belmokhtar
Mustapha Belmokhtar

Reputation: 1219

Get rid of all the blank spaces before summing the length :

  s=s.replaceAll("[ \n\t]+","");
  numberOfLetters += s.length();

Upvotes: 0

Related Questions