JAVA indexOf - counting strings against the alphabet

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

IncubusJaxAsked:
Who is Participating?
 
Kevin CrossChief Technology OfficerCommented:
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.
0
 
CEHJCommented:
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')]

0
 
IncubusJaxAuthor 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!
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

 
Kevin CrossChief Technology OfficerCommented:
Hint:
int ch = 65;
System.out.println((char)ch);

Will result in 'A'.
0
 
IncubusJaxAuthor Commented:
Thank you all, this helps. I'll get back on it. ;)
0
 
IncubusJaxAuthor 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

0
 
objectsCommented:
>                     System.out.println(+ch +"  " +count);


change that to

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


0
 
IncubusJaxAuthor Commented:
I knew it was something dumb.

Thanks everyone. Points all around! ;)
0
 
CEHJCommented:
Better to do
System.out.printf("%s=%d\n", ch, count);

Open in new window

0
 
IncubusJaxAuthor 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... :)
0
 
CEHJCommented:
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
0
 
IncubusJaxAuthor 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. ;)
0
 
objectsCommented:
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 :)

0
 
Kevin CrossChief Technology OfficerCommented:
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

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

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.