Results 1 to 4 of 4
- 02-28-2013, 03:05 PM #1
Member
- Join Date
- Feb 2013
- Posts
- 60
- Rep Power
- 0
Program not counting all of the letters its suppose to be
I'm writing a program that will count the number of occurrences of a certain letter. This is my code and my current output. The answer of the output is '8' while I'm only getting '7'. Does anybody see the problem? I can't use Arrays for this problem.
Output:Java Code:public int letterCount(char c) { int total = 0; for (int i=0; i< m_str.length(); i++) { if (Character.isUpperCase(m_str.charAt(i))) total++; } return total; }
Starting with: She Sells Sea Shells Down by the Sea Shore
Number of s's = 7
- 02-28-2013, 03:12 PM #2
Senior Member
- Join Date
- Jan 2013
- Location
- United States
- Posts
- 686
- Rep Power
- 1
Re: Program not counting all of the letters its suppose to be
You are counting upper case letters, not occurrences of a specific letter.
There are a number of ways to approach the problem. But first you need to determine if this is a case-sensitive count or not.
JimThe Java™ Tutorial
YAT -- Yet Another Typo
- 02-28-2013, 03:25 PM #3
Member
- Join Date
- Feb 2013
- Posts
- 60
- Rep Power
- 0
Re: Program not counting all of the letters its suppose to be
I don't want it to be case sensitive, but when I tried other methods it started returning the number of total letters in the sentence and not the number of s's
- 02-28-2013, 03:32 PM #4
Senior Member
- Join Date
- Jan 2013
- Location
- United States
- Posts
- 686
- Rep Power
- 1
Re: Program not counting all of the letters its suppose to be
Okay. It will be case-insensitive. But notice that you are not comparing the supplied character to anything. Before coding you need to think of a strategy or general approach. Here is an example:
- Get the character to count.
- Compare this character to each character in the string.
- If a match, increment count.
Now that is a reasonable start. However, in the general case, it will not work correctly. What happens if someone wants to count all the c's so they provide a C as an argument.
To test this you might want to put in strings of the same character but mix up the case and see what happens. And as always, put in print statements to help debug.
Regards,
JimThe Java™ Tutorial
YAT -- Yet Another Typo
Similar Threads
-
how to do these program letters with values
By w0ooop in forum NetBeansReplies: 16Last Post: 02-20-2013, 03:26 PM -
Finding & counting certain letters in a sentence
By LetsG0Blue in forum New To JavaReplies: 1Last Post: 02-19-2013, 07:15 AM -
counting letters in a string
By beandip408 in forum New To JavaReplies: 12Last Post: 09-29-2010, 01:44 PM -
Need help with a program that takes letters and then dumps them back out
By Adde1986 in forum New To JavaReplies: 2Last Post: 04-09-2009, 10:46 PM -
Need help with counting letters
By mrdestroy in forum New To JavaReplies: 15Last Post: 10-22-2008, 01:33 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks