1

I need to count the frequency at which a letter appears in a string.

To do this, I thought about using a scanner object, passing the string to it

Scanner s = new Scanner(String)

and using the next() method to analyse each char with a switch statement.

I've done a search on these boards and have devised the following :-

for (int i = 0; i < outputString.length(); i++) {
    Scanner s = new Scanner(outputString);
    char letter = s.next().charAt(i);
    switch (letter) {
    switch code;
}

This appears to work when the string I'm analysing contains anything (-_z1 etc..) other than whitespaces which will cause the program to throw a String.IndexOutOfBoundException (4).

Is there something else I can try or should I just remove all the whitespaces from the word (i.e. I'm thinking by creating a newword string using a for loop to add each string.charAt(i) != ' ').

Edit: I forgot that the scanner was in the for loop, I'll take it out. Secondly, not sure if it changes matters but I'm trying to count the no of times each letter in the alphabet in the string appears, not just one type of letter. Thanks for your comments!

Thanks in advance,

kevin0110w
  • 43
  • 3
  • This code doesn't make much sense. If the goal is to go through each letter of outputString, why are you creating a Scanner and calling next(), instead of just getting the character at index i of outputString directly? – JB Nizet Nov 11 '18 at 15:31
  • I understand what you are trying to achieve but this is a complicated way. Why not get the String in a String object and then manually check directly? – Taslim Oseni Nov 11 '18 at 15:32
  • @JBNizet - I'm not sure, it must have skipped my mind. I've now changed it to outputString.charAt(i) which is much more cleaner - no need to remove any spaces! – kevin0110w Nov 13 '18 at 11:06

5 Answers5

0

Here is an alternative way to solve this problem provided on another question. (can't leave comments yet.. so have to put as an answer...) How to count frequency of characters in a string?

Perry Moen
  • 41
  • 5
0

I strongly think you're complicating things by using that approach. You can simply pass the String (and the char you are searching for) into a method just like the one below:

public int checkFreq(char letter, String word){
    int freq = 0;

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

    return freq;
}

I hope this helps.. Merry coding!

Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
0

While having this:

Scanner s = new Scanner(outputString);

Inside the for loop, you're creating a new Scanner in every iteration (not efficient nor what you want).

If you already have a String called outputString you can access its characters / letters directly as follows:

for (int i = 0; i < outputString.length(); i++) {
    char letter = outputString.charAt(i);
    //The rest of you code here
}
Frakcool
  • 10,915
  • 9
  • 50
  • 89
0

You should follow the above solution for getting repeated characters in a string. However, I will just give you a hint about why you are getting the exception

consider the following code:

String outputString = "Pre ";
for (int i = 0; i < outputString.length(); i++) {
      Scanner s = new Scanner(outputString);
      System.out.println(outputString.length()); // output is 4
      System.out.println(s.next().length()); //output is 3, not considering the space
      //char letter = s.next().charAt(i);
      //System.out.println(letter);
  }
0

First of all, you shold not create new Scanner each time when you ready next character. Do it only once, before for loop.

Second - to read scanner character by character, you have set delimeter as "". In this case, scan.next() returns next character.

Third - you use Scanner to analyze string, that's OK (not optimal and overhead, but OK). Then do create new Scanner isntance and rely on it's data, but not on length of the goven string; do use Scanner.hasNext() method. I mean that all you need, is just add hasNext() to be sure that more characters exists in the scanner's stream:

try (Scanner scan = new Scanner(outputString)) {
    scan.useDelimiter("");  // to make scan.next() return one single character

    while (scan.hasNext()) {
        char ch = scan.next().charAt(0);    // next() returns String with one character
        // do your work
    }
}

P.S. This is code examples, how you can cound character frequencey in the given string with different ways. Probably, one of them you'll find more relevant to your task.

// this is your approach
public static int characterFrequency(String str, char ch) {
    try (Scanner scan = new Scanner(str)) {
        scan.useDelimiter("");
        int count = 0;

        while (scan.hasNext())
            count += scan.next().charAt(0) == ch ? 1 : 0;

        return count;
    }
}

// this one is the most efficient
public static int characterFrequency(String str, char ch) {
    int count = 0;

    for (int i = 0; i < str.length(); i++)
        count += str.charAt(i) == ch ? 1 : 0;

    return count;
}

// this one is the smallest of code
public static int characterFrequency(String str, char ch) {
    return (int)str.chars().filter(e -> e == ch).count();
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35