We help IT Professionals succeed at work.

JAVA indexOf - counting strings against the alphabet

IncubusJax
IncubusJax asked
on
Medium Priority
2,155 Views
Last Modified: 2013-11-23
Hey everyone,

Sorry to ask about a homework assignment, but I'm at my wits end.

I have a two part assignment.

The first part was to, using indexOf, ask the user for a string and then ask for a character. Then search the string and count how many times that character appears in the string.

So if the string was "hello"
and the character was "l"

The output would be 2.

This I've got and I'll post the code below.

My problem is the second half of the exercise which is:

Create another app based on the First one that asks a user for a string. Take that string and compare it against the alphabet and count how many letters of the alphabet appear in the string.

So here would be a sample output:

if the string was "abc"
output would be

a = 1
b = 2
c = 3
d = 0
e = 0
f = 0
g = 0

and so on to z = 0.

I've probably rewritten this code a million times. I think I might be able to do it with an if statement and a variable for each letter of the alphabet, but I just don't accept that as the solution. I know it should be easier.

Any hints, suggestions or pointers would be great. Again, sorry to ask about homework, I'm just not sure where to go from here.

Thank You all!

Mark


import java.awt.Component;
 
import javax.swing.*;
 
public class Index 
{
	private static Component frame;
 
	public static void main(String[] args)
	{
		String s = JOptionPane.showInputDialog("Please Enter a String");
		String c = JOptionPane.showInputDialog("please Enter a Charecter");
		
		int count = 0;
		int index = 0;
		
		while((index = s.indexOf(c, index )) >= 0 )
		{
			count++;
			index++;
		}
		
		JOptionPane.showMessageDialog(frame,"There are "+count +" of those charecters in your string.");
	}
}

Open in new window

Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2016
Commented:
I don't want to do your homework for you, but i'll give you some clues:

a. create counts int[26]
b. use String.charAt
c. address array:
counts[(int)(Character.toUpperCase(c) - 'A')]

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
Thanks, I see what I can come up with.

Yeah, not trying to get anyone to do it for me, I'm just trying to figure out what I'm missing/give me a nudge you know.

Thanks a lot!
Chief Technology Officer
CERTIFIED EXPERT
Most Valuable Expert 2011
Commented:
If you have to still use indexOf as specified in the first part of the assignment, then you can try something like this:

+create counts int[26] (like CEHJ suggests)
+convert input string to all uppercase using toUpperCase
+use the fact that ASCII characters for A-Z in uppercase are 65 - 90 and create a for loop surrounding your while statement that starts at 65 and loops until you reach 90
+indexOf function takes in an int which represents character, you can then update you count by subtracting 'A' or 65 from the current value you are on in your loop.
Kevin CrossChief Technology Officer
CERTIFIED EXPERT
Most Valuable Expert 2011
Commented:
Hint:
int ch = 65;
System.out.println((char)ch);

Will result in 'A'.

Author

Commented:
Thank you all, this helps. I'll get back on it. ;)

Author

Commented:
Okay,

So, based on your great hints and suggestions, here's what I got (below in snippet), which works great.

Except... it outputs in NUMBERS, so it's not coming back to letters.

Drats!

Am I missing something simple and stupid here?

Thanks


import javax.swing.*;
import java.awt.Component;
 
public class Index2
{
	private static Component frame;
 
	public static void main(String[] args)
	{
		String s = JOptionPane.showInputDialog("enter a string");
		String upperString = s.toUpperCase(); //converts input string to all upper case.
 
		int count = 0;
		int index = 0;
		char ch; // Letter being searched
		 
		for (int x = 65; x <= 90; x++) // for loop to go from A..Z
		{
		  ch = (char)x;  // Convert to searchable letter
		   while((index = upperString.indexOf(ch, index )) >= 0 )
		    {
		        count++;
		        index++;
		    }
		    System.out.println(+ch +"  " +count);
		    //JOptionPane.showMessageDialog(frame,+ch +" " +count);
		   count = 0; // reset count to 0 for next letter
		    index = 0; // reset index to 0 for next letter
		}
 
	}
}

Open in new window

Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
>                     System.out.println(+ch +"  " +count);


change that to

                    System.out.println(ch +"  " +count);


Author

Commented:
I knew it was something dumb.

Thanks everyone. Points all around! ;)
CERTIFIED EXPERT
Top Expert 2016

Commented:
Better to do
System.out.printf("%s=%d\n", ch, count);

Open in new window

Author

Commented:
Interesting. I'll try that out. I still have to code this into a "GUI" so I'll be playing with it for a little while longer anyway. I like to do the logic old school then add in all the other stuff afterwards... :)
CERTIFIED EXPERT
Top Expert 2016

Commented:
Bear in mind that your solution, although working, is inefficient - you read the string length*26 times. In the way i suggested, you'd read it once only

Author

Commented:
Yeah I noticed that. Thanks for the heads up. I'll play around with it now that I've got a proof of concept going. Maybe my feeble mind can get it to work a little better. ;)
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
We've got some examples we've used here in the past. When you're done give me a yell if you are interested in comparing :)

Kevin CrossChief Technology Officer
CERTIFIED EXPERT
Most Valuable Expert 2011

Commented:
Glad that helped you.  Definitely more effecient other ways, but since you had a specific homework assignment stating to use indexOf; I don't think efficiency is the concern -- do the assignment. :)  IMHO

By the way, here is a condensed version based on the approach you are using above.  If you are able to change methods, as CEHJ stated just let us know.
public static void main(String[] args) {
        String s = JOptionPane.showInputDialog("Please Enter a String");
        //String c = JOptionPane.showInputDialog("please Enter a Charecter");
 
        for (int ch = 65; ch <= 90; ch++) {
            int index = 0;
            int count = 0;
 
            while ((index = s.toUpperCase().indexOf(ch, index)) >= 0) {
                count++;
                index++;
            }
 
            System.out.println((char)ch + " " + count);
        }
    }

Open in new window

CERTIFIED EXPERT
Top Expert 2016

Commented:
The following will make your intentions clearer:
for (int ch = 'A'; ch <= 'Z'; ch++) {

Open in new window

Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.