user2918429
user2918429

Reputation: 53

Count the occurrences of a letter in a string

I am trying to write a for loop in Java that will count the occurrences of a letter in a string. The user will enter the letter to count and the string in which to search. This is a very basic code, and we have not gotten to arrays or much else yet. (I realize that I declared letter twice, but my brain is dead at this point) This is what I have tried so far and am having trouble with, any help is appreciated:

Ok I changed my code per suggestions, but now it is only reading the first word of my sentence?

import java.util.Scanner;

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

    char letter;
    String sentence = "";
    System.out.println("Enter a character for which to search");
    letter = in.next().charAt(0);
    System.out.println("Enter the string to search");
    sentence = in.next();

    int count = 0;
    for (int i = 0; i < sentence.length(); i++) {
        char ch = sentence.charAt(i);
        if (ch == letter) {
            count++;
        }
    }
    System.out.printf("There are %d occurrences of %s in %s", count,
            letter, sentence);

}
}

Upvotes: 3

Views: 30230

Answers (10)

Learnaholic
Learnaholic

Reputation: 175

your Scanner class has not moved to the next line after reading the character

letter = in.next().charAt(0);

add another in.nextLine() before reading the input string

    System.out.println("Enter a character for which to search");
    letter = in.next().charAt(0);
    in.nextLine();
    System.out.println("Enter the string to search");
    sentence = in.nextLine();

old thread but hope this helps :)

Upvotes: 0

Ameya Jadhav
Ameya Jadhav

Reputation: 1

try the indexOf() method. it should work

Upvotes: 0

Anto Robinson
Anto Robinson

Reputation: 463

Hope this will helpful to you.

import java.util.Scanner;

public class CountCharacters {
    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        System.out.println("Enter the string to search");
        String sentence = in.nextLine();

        System.out.println("Enter a character for which to search");
        String letter = in.next();

        int noOfOccurance = 0;

        for (int i = 0; i < sentence.length(); i++) {
            char dh=letter.charAt(0);
            char ch = sentence.charAt(i);
            if (dh==ch) {
               noOfOccurance++;
            }
       }
       System.out.print(noOfOccurance);
    }
}

Sample Input Output:

Enter the string to search
how are you
Enter a character for which to search
o
No of Occurances : 2

Upvotes: 0

Mengjun
Mengjun

Reputation: 3197

  1. You need to know the char you wanna search. You can use char charToSearch = letter.toCharArray()[0];
  2. Define a variable, such as count to count the occurrences of a letter in a given string.
  3. Loop the string and compare each char, if the char is equal to the char to search, then count++;

Example--->

int count = 0;
char charToSearch = letter.toCharArray()[0];
for (int i = 0; i < sentence.length(); i++) {
    if (sentence.charAt(i) ==  charToSearch) {
        count++;
    }
}

System.out.printf("Occurrences of a %s in %s is %d", letter, sentence, count);

Upvotes: 0

Nizam
Nizam

Reputation: 5731

Try this:

Char letter = '';
String sentence = "";
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();

int count= 0;
for (int i = 0; i < sentence.length(); i++) {
    char ch = sentence.charAt(i);
    if (ch==letter) {
        count++;
    }
}
System.out.print(letter+" occurance:"+count);

Upvotes: 0

Paul Samsotha
Paul Samsotha

Reputation: 208994

Try this

forget String letter = "" <-- Delete
forget letter = in.next() <-- Delete

    // There's no nextChar() method, so this is a work aroung
    char ch = in.findWithinHorizon(".", 0).charAt(0);

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

        if (sentence.charAt(i) == ch) {
            letter++;
        }
    }

    System.out.println(letter);  // print number of times letter appears

    // You don't want this
    System.out.print(sentence.charAt(letter)); // Makes no sense

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53525

No need to loop:

    String sentence = "abcabcabcd";
    String letter = "b";
    int numOfOccurences = sentence.length() - 
                          sentence.replaceAll(letter, "").length();
    System.out.println("numOfOccurences = "+numOfOccurences);

OUTPUT:

numOfOccurences = 3

Upvotes: 0

Francis
Francis

Reputation: 1090

I see a couple of issues. First you have two variables with the same name.

Second your if condition check for the lenght of the sentence to be greater then 0 instead of checking for character equality.

Scanner in = new Scanner(System.in);

char inLetter = "";
String sentence = "";
System.out.println("Enter a character for which to search");
inLetter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();

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

System.out.print(sentence.charAt(letter));

I would also strongly suggest to validate the input (which is not done in the example above) instead of just assuming you got 1 character from the first input and 1 sentence in the second.

Upvotes: 1

if (sentence.length() <= 0) {
            letter++;
}

The above part of code in your program is wrong. This will never be true until otherwise you input an empty string.

And basically this is not the correct logic. You will have to use the direct comparison.

Upvotes: 0

Masudul
Masudul

Reputation: 21961

Your if (sentence.length() <= 0) { is not right. Change your condition like:

System.out.println("Enter a character for which to search");
letter = in.next();
System.out.println("Enter the string to search");
sentence = in.next();
char searchLet=letter.charAt(0); // Convert String to char
int letter = 0;
for (int i = 0; i < sentence.length(); i++) {
    char ch = sentence.charAt(i);
    if (searchLet== ch) {  // Check the occurrence of desired letter.
        letter++;
    }
}

System.out.print(sentence.charAt(letter));

Upvotes: 0

Related Questions