-2

This is my code for a program that should count the number of each letter in an inputted string. When I run the program, it says that there is 0 of each letter, no matter what I input. Thanks for the help in advance!

import java.util.Scanner;

public class stringprogram {
    public static void stringinputmethod()
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a String");
        String strs = scan.nextLine();
        int strslength = strs.length();

        int numa = 0;
        int numb = 0;
        int numc = 0;
        int numd = 0;
        int nume = 0;
        int numf = 0;
        int numg = 0;
        int numh = 0;
        int numi = 0;
        int numj = 0;
        int numk = 0;
        int numl = 0;
        int numm = 0;
        int numn = 0;
        int numo = 0;
        int nump = 0;
        int numq = 0;
        int numr = 0;
        int nums = 0;
        int numt = 0;
        int numu = 0;
        int numv = 0;
        int numw = 0;
        int numx = 0;
        int numy = 0;
        int numz = 0;

        for(int i = 0; i <= strslength; i++)
        {
            if (strs.substring(i, i) == "a")
            {
                numa = numa + 1;
            }
            if (strs.substring(i, i) == "b")
            {
                numb = numb + 1;
            }
            if (strs.substring(i, i) == "c")
            {
                numc = numc + 1;
            }
            if (strs.substring(i, i) == "d")
            {
                numd = numd + 1;
            }
            if (strs.substring(i, i) == "e")
            {
                nume = nume + 1;
            }
            if (strs.substring(i, i) == "f")
            {
                numf = numf + 1;
            }
            if (strs.substring(i, i) == "g")
            {
                numg = numg + 1;
            }
            if (strs.substring(i, i) == "h")
            {
                numh = numh + 1;
            }
            if (strs.substring(i, i) == "i")
            {
                numi = numi + 1;
            }
            if (strs.substring(i, i) == "j")
            {
                numj = numj + 1;
            }
            if (strs.substring(i, i) == "k")
            {
                numk = numk + 1;
            }
            if (strs.substring(i, i) == "l")
            {
                numl = numl + 1;
            }
            if (strs.substring(i, i) == "m")
            {
                numm = numm + 1;
            }
            if (strs.substring(i, i) == "n")
            {
                numn = numn + 1;
            }
            if (strs.substring(i, i) == "o")
            {
                numo = numo + 1;
            }
            if (strs.substring(i, i) == "p")
            {
                nump = nump + 1;
            }
            if (strs.substring(i, i) == "q")
            {
                numq = numq + 1;
            }
            if (strs.substring(i, i) == "r")
            {
                numr = numr + 1;
            }
            if (strs.substring(i, i) == "s")
            {
                nums = nums + 1;
            }
            if (strs.substring(i, i) == "t")
            {
                numt = numt + 1;
            }
            if (strs.substring(i, i) == "u")
            {
                numu = numu + 1;
            }
            if (strs.substring(i, i) == "v")
            {
                numv = numv + 1;
            }
            if (strs.substring(i, i) == "w")
            {
                numw = numw + 1;
            }
            if (strs.substring(i, i) == "x")
            { 
                numx = numx + 1;
            }
            if (strs.substring(i, i) == "y")
            {
                numy = numy + 1;
            }
            if (strs.substring(i, i) == "z")
            {
                numz = numz + 1;
            }
        }
        System.out.println("Number of a's: " + numa + "\n" + "Number of b's: " + numb + "\n" + "Number of c's: " + numc + "\n" + "Number of d's: " + numd + "\n" + "Number of e's: " + nume + "\n" + "Number of f's: " + numf + "\n" + "Number of g's: " + numg + "\n" + "Number of h's: " + numa + "\n" + "Number of i's: " + numi + "\n" + "Number of j's: " + numj + "\n" + "Number of k's: " + numk + "\n" + "Number of l's: " + numl + "\n" + "Number of m's: " + numm + "\n" + "Number of n's: " + numn + "\n" + "Number of o's: " + numo + "\n" + "Number of p's: " + nump + "\n" + "Number of q's: " + numq + "\n" + "Number of r's: " + numr + "\n" + "Number of s's: " + nums + "\n" + "Number of t's: " + numt + "\n" + "Number of u's: " + numu + "\n" + "Number of v's: " + numv + "\n" + "Number of w's: " + numw + "\n" + "Number of x's: " + numx + "\n" + "Number of y's: " + numy + "\n" + "Number of z's: " + numz);
    }
    public static void main(String[] args)
    {
        stringinputmethod();
    }
}
Young Deezie
  • 145
  • 2
  • 12
  • 8
    **Please** learn about arrays. It is no fun reading someone else's code that has the same thing repeated 26 times. – ajb Jan 12 '15 at 17:55
  • 1
    Also consider using a proper naming convention. camel-case for methods (e.g. `stringInputMethod`) and the first character of classes should be upper case (e.g. `StringProgram`). – th3falc0n Jan 12 '15 at 17:57
  • 2
    you should either take theFalcons answer AND use the equals method. Or you can use the charAt(i) method to use == operator, but you need to use singlequote chars then like 'a' – Simon Meyer Jan 12 '15 at 18:00
  • 1
    Maybe even use `equalsIgnoreCase()` in case the user enters in a capital letter as well – Ascalonian Jan 12 '15 at 18:00

3 Answers3

3

Correct usage of the substring method:

strs.substring(i, i)

needs to be

strs.substring(i, i + 1)

because the char at lastIndex is not included in the output.

Correct comparison of Strings in Java

Also, as pointed out in the comments to this answer, you are comparing Strings with the == operator. This will only works as long as both your Strings are the same object. For proper comparison you need to use strs.substring(..).equals()

Proper storing of data

Additionally, as already suggested in a comment to your question, you should start using arrays to save data like this.

th3falc0n
  • 1,389
  • 1
  • 12
  • 33
2

Instead of

int numa = 0;
....
int numz = 0;

you should use arrays, or even better Map<Character,Integer>.

strs.substring(i, i) == "a" have two problems:

  • substring(i, i) creates string from i (inclusive), till i (exclusive) which means it creates empty string ""
  • this is not how we compare Strings. == may work sometimes if strings are pooled, but for dynamically created strings you need to use equals instead of == because Strings are objects, or even better use charAt(i) to get primitive char which you can be able to compare like strs.charAt(i) == 'a' (notice ' instead of ").

You can also use enhanced for loop on array of characters representing your string to avoid charAt. You should probably also be working on lower case characters as pointed in this comment. So your code can look more like

for (char ch : strs.toLowerCase().toCharArray()){
    //do something based on value of `ch`
}
Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

Try this:

It is a little bit shorter than your implementation (which is very good, but still a little bit verbose). Use Java 8 with this code, otherwise it won't compile.

What does it do? If you understand that a string is nothing more but an array you can iterate over that array and see what kind of value is at the given index. The value at this index is put in a map (remember, a map is a key-value-store). So if you put the Integer 1 in the map where its key is "a", that means "a" occurs 1 time. By reading the values at the appropriate indexii (very sophisticated plural form of index) with HashMap.get("a") and then incrementing the value by one, we have a nice little letter counter... without the need to predefine numa=0 and so forth. Give it a try and let me know if it werx.

package lettercounter;

import java.util.Arrays;
import java.util.HashMap;
    import java.util.Scanner;

    /**
    *
    * @author edm
    */
    public class LetterCounter {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a String");
        String strs = scan.nextLine();
        //this map will be populated with the occurrence of the letters in the string.
        HashMap<String, Integer> countenLetters = new HashMap<>();
        //the next line generates a key-value-store whose key is the letter in the string
        //and the value is the accumulated occurrence of said letter.
        Arrays.asList(strs.split("")).stream().forEach((String letter) -> {
            Integer count = 0;
            try {
               count = countenLetters.get(letter).intValue(); 
            } catch (Exception e) {
                //tried to access a non existing value in the map
                //this happens if there is a letter which was not set in the map until now.
                //i.e. the first time the letter is encountered.
                //this is no error. could have done it with an if also.
            }
            countenLetters.put(letter, ++count);

        });
        //do with this stuff what you want;
        countenLetters.forEach((k,v) -> {
            System.out.println("Letter "+k+" occurs "+v+" times in the string.");
        });
    }

}
easyDaMan
  • 308
  • 3
  • 8
  • HashMap actually means: The key of the HashMap is of type String, and the value is of type Integer. It occurred to me that I might need to explain that. Might I ask how much programming experience you have? Depending on your reply, I might need to go into a little bit more detail in regard to my answer. – easyDaMan Jan 12 '15 at 19:12