0

So our teacher gave us this homework, we had to write a program that went something along the lines of

Write an application that reads a line of text from the keyboard and prints a table indicating the number of occurrences of each letter of the alphabet in the text, For example, the phrase

To be, or not to be: that is the question:

Contains one “a,” two “b’s,” no “c’s,” and so on.

Well I've written the code, but I've ran into one small problem when I enter the to be or not to be part the code continually loops forever. I've looked at this program forever, I even tried asking some folks at Yahoo (but I think I confused them). So I am hoping someone here will spot something I missed or have some advice to give me.

public class occurances {
    public static void main(String[] args) {
        Scanner inp = new Scanner(System.in);
        String str;
        char ch;
        int count = 0;

        System.out.println("Enter the string:");
        str = inp.nextLine();

        while (str.length() > 0) {
            ch = str.charAt(0);
            int i = 0;

            while (i < str.length() && str.charAt(i) == ch) {
                count = count++;
                i++;
            }

            str = str.substring(count);
            System.out.println(ch);
            System.out.println(count);
        }
    }
}
5
  • 3
    What do you think count++ does? Commented Mar 20, 2015 at 9:13
  • I do not see a loop terminating condition for the inner while loop. Commented Mar 20, 2015 at 9:15
  • It seems to me that your while loop conditions need revisiting. Commented Mar 20, 2015 at 9:18
  • Possible Duplicate: stackoverflow.com/questions/6945707/java-operator-problem Commented Mar 20, 2015 at 9:19
  • I did the count++ because I wanted to increase the overall count of each individual character has they occurred, but I'll run back over my loop and see Commented Mar 20, 2015 at 9:20

5 Answers 5

3

There are many problems with your code, but start with count = count++. It will always have its initial values (0 in your case). That causes the infinite loop. If you manage this one you'll be good to go with debugging your code further. Learn how to use debugger and/or print for checking your code. Good luck.

Sign up to request clarification or add additional context in comments.

1 Comment

This answer from the suggested duplicate explains why this doesn't work.
2

It seems your approach is not necessarily the one the teacher wants. Your approach (if it worked at all) would display the character counts in the order the characters appear in the string. So, for example, for "To be, or not to be: that is the question" you would show the character count for "T" first, whereas the teacher probably wants you to show the character count for "a" first. Your approach also doesn't show the character counts for the characters that are missing in the answer.

It has been suggested in the other two answers to use a Map. I recommend that approach, although you could use a simple int[] array where the index is (ch - 'a') assuming that it is between 0 and 25. See Character.toLowerCase() for how to convert a character into a lowercase one, because the correct answer would probably treat "T" and "t" as the same.

You need only one loop through the array, incrementing the counts for the characters that appear. Obviously all of the counts should be initialized to 0 prior to the loop.

1 Comment

Good idea to substitute an array for a map.
0

I've not done JAVA in a while i came here to help someone with Javascript... but i'll give it go

while(str.length()>0)

This will obviously enter an endless loop because you have no breakout terms... i'd probably use a for loop instead... also you need something to store your counts inside of for each unique letter you find.

-- EDIT based on the comment below i find myself agreeing that answering your homework is not a good thing but here is what i'd suggest you look at...

  1. Look at Hashtables or Maps and thing about "storing the dictionary counts as you find them"
  2. Bare in mind upper and lower case letter, i'd just cast to lowercase and count
  3. use a for loop instead of the while loop, use the strings length as the limit e.g. count from 0 to string.length()

This should get you on the right path :http://www.java2s.com/Tutorial/Java/0140__Collections/GettingelementskeyvaluepairsfromaHashtabletheentrySetmethod.htm

Comments

0

Some things to resolve in your code:

  • while(str.length()>0) : Infinite loop here. You could go through the string, with a for (int index = 0; index < str.length(); index++).
  • ch = str.charAt(0); : Here you are always taking the first letter of the String, you should take each letters with ch = str.charAt(index);.
  • count = count++; : count++; would be enough or count = count + 1;.
  • count = count++; : count should be re-initialized for each letter count = 0; before your while inner loop.
  • str = str.substring(count); : No need to substring here. You would loose letters for next computation.

Your code should work with one disavantages. The letters and their count will be written as many times as their is their occurence. If a is 3 times in the String, a : 3 will be written 3 times.

So you should whether you had already print the letter (maybe an array), but performance would be bad. For a String of n letters, you would have n * n computations (Complexity O(n^2)). If you take an HashMap between letter and their count, you will just of to go through the String one time, incrementing your counter while iterating on the loop. Then you would have only n computations. (Complexity O(n)).

HashMap<Char, Integer> letters = new HashMap<Char, Integer>();
for (int i = 0; i < str.length(); i++) {
   char letter = str.charAt(i);
   if (!letters.contains(letter)) {
     letters.put(letter, 1);
   } else {
     letters.put(letter, letters.get(letter) + 1);
   }
}

Then you go through the map to display the count.

3 Comments

Down-vote from me. It's personal preference, but I don't like to see homework-esque questions answered with full working code. It ruins the opportunity to learn properly. Nor did you really explain much about why the current approach is wrong.
Agree with you. That's what I thought writting the answer, but I'm new here. Is it better now ?
Duncan, still -1 after all the explanations ?
0

Here is your corrected code for the problem you asked..Try this..

import java.util.*;

public class Occurence {
    public static void main(String[] args) {
        Scanner inp = new Scanner(System.in);
        String str;
        char ch;
        int count = 0;

        System.out.println("Enter the string:");
        str = inp.nextLine();
        int length = str.length();
        int i = 0, j = 0;

        for (i = 0; i < length; i++) {
            j = 0;
            count=0;

            for (j = 0; j < length; j++) {
                if (str.charAt(j) == str.charAt(i)) {
                    count++; 
                }

                System.out.println(str.charAt(i)+" "+count); 
            }
        }
    }
}

1 Comment

please check that i have modified the code wherever it is required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.