Arcee
Arcee

Reputation: 149

Count using Enhanced for loop

I have this code below, my goal is to count how many letter 'e' is in the String "abcdee".

class Sample1 {
    String tiles;

    public Sample1 (String tiles) {
        this.tiles = tiles;
    }

    public int countLetter(char letter) {
        int a = 0;      
        for (char x : tiles.toCharArray()) {
            int m = 0;
            if (tiles.indexOf(letter) != -1) {
                m = 1;
            }
            a += m;
            System.out.println("Letter count is " + m); 
        }
        return a;
    }
}

public class Sample {

    public static void main(String[] args) {
        Sample1 s = new Sample1("abcdee");
        s.countLetter('e'); 

    }
}

I expect that the code would give me this result:

Letter count is 0
Letter count is 0
Letter count is 0
Letter count is 0
Letter count is 1
Letter count is 1

and then maybe add all the 1's to get 2. But all I get is this when I run it:

Letter count is 1
Letter count is 1
Letter count is 1
Letter count is 1
Letter count is 1
Letter count is 1

Hope you can help me out.

Upvotes: 2

Views: 846

Answers (3)

Ray Toal
Ray Toal

Reputation: 88378

The easiest way to fix your code is to change the logic in your counting method to

    int a = 0;      
    for (char x : tiles.toCharArray()) {
        if (x == letter) {
            a += 1;
        }
    }
    return a;

There are better ways, though.

You might want to look as this old Stack Overflow question which is a more general solution to the problem you are working on.

Upvotes: 3

Snehal
Snehal

Reputation: 11

The indexOf(String target) method searches left-to-right inside the given string for a "target" string. The indexOf() method returns the index number where the target string is first found or -1 if the target is not found. So if 'e' is present it would return true . You have not used variable x anywhere in your loop first of all .Maybe you can try ,

if (x == letter) {
  a+ = 1
}

instead of

if (tiles.indexOf(letter) != -1) {
  m = 1;
}

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56433

It's repeatedly printing 1 because you're using indexOf method, that means as long as the letter e exists within the string tiles it will always print Letter count is 1.To solve the problem at hand simply change:

if (tiles.indexOf(letter) != -1)

to:

if (x == letter)

An even simpler solution to return the letter count as of java-8 is:

public int countLetter(char letter) {
       return (int)tiles.chars().filter(e -> e == letter).count();
}

Upvotes: 0

Related Questions