1
String sentence = JOptionPane.showInputDialog (null, "Write a sentence.");    
String letter = JOptionPane.showInputDialog(null, "Write a letter");

while (true) {

    if (letter.equals("Stop"))
        System.exit(0);    
    //to calculate number of specific character
    else {
        int countLetter = 0;
        int L = letter.length();
        for (int i = 0; i < L; i++) {
            if ((letter.charAt(i) = .....))     
                countLetter++;
        }
    }
}

Is it possible to replace the dots to make the program count how many times the given letter occures in the sentence written in the first string?

deHaar
  • 17,687
  • 10
  • 38
  • 51
  • 1
    Sure, but it's `==`, not `=` and you may want to cycle through `sentence` too. In other words, you're missing a piece of code other than `.....` – Federico klez Culloca Nov 21 '18 at 10:44
  • Welcome to Stack Overflow, Sandra. Go through your code one more time, I think you have some errors in your thinking here. You are iterating over the characters in `letter`, but `letter` should only contain **one letter**, right? So iterating over its seems like a mistake to me. I think you should replace it with `sentence` in your code and then check `sentence.charAt(i) == letter.charAt(0)` – Neuron Nov 21 '18 at 12:59

4 Answers4

3

Since Java 8, there is an elegant solution to this.

int count = letter.chars().filter(ch -> ch == 'e').count();

This will return the number of occurences of letter 'e'.

Willy Wonka
  • 138
  • 2
  • 11
0

if your String letter contains a one character use this letter.charAt(0) and then replace dots with this. Also remember to use == instead of = here. = means you are just asigning and == uses to compare two values.

Sandeepa
  • 3,457
  • 5
  • 25
  • 41
0

If you have to use a for loop and want to stick to the old fashioned way, try this:

    String sentence = "This is a really basic sentence, just for example purpose.";
    char letter = 'a';

    int occurrenceOfChar = 0;

    for (int i = 0; i < sentence.length(); i++) {
        if (sentence.charAt(i) == letter) {
            occurrenceOfChar++;
        }
    }

    System.out.println("The letter '" + letter
            + "' occurs " + occurrenceOfChar
            + " times in the sentence \""
            + sentence + "\"");

The sentence and the letter are just examples, you have to read the user input.

deHaar
  • 17,687
  • 10
  • 38
  • 51
0

You can use Guava Lib to perform this operation faster without iterating string.

CharMatcher.is('e').countIn("Write a letter");

Will return 3

Ravi Sapariya
  • 395
  • 2
  • 11