Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

JAVA indexOf - counting strings against the alphabet

Posted on 2009-02-12
15
Medium Priority
?
2,104 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

0
Comment
Question by:IncubusJax
  • 6
  • 4
  • 3
  • +1
15 Comments
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 400 total points
ID: 23625871
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
 

Author Comment

by:IncubusJax
ID: 23626005
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
 
LVL 61

Accepted Solution

by:
Kevin Cross earned 1200 total points
ID: 23626035
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 61

Assisted Solution

by:Kevin Cross
Kevin Cross earned 1200 total points
ID: 23626047
Hint:
int ch = 65;
System.out.println((char)ch);

Will result in 'A'.
0
 

Author Comment

by:IncubusJax
ID: 23626108
Thank you all, this helps. I'll get back on it. ;)
0
 

Author Comment

by:IncubusJax
ID: 23627659
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
 
LVL 92

Assisted Solution

by:objects
objects earned 400 total points
ID: 23627693
>                     System.out.println(+ch +"  " +count);


change that to

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


0
 

Author Comment

by:IncubusJax
ID: 23627756
I knew it was something dumb.

Thanks everyone. Points all around! ;)
0
 
LVL 86

Expert Comment

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

Open in new window

0
 

Author Comment

by:IncubusJax
ID: 23627882
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 23627926
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
 

Author Comment

by:IncubusJax
ID: 23628221
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
 
LVL 92

Expert Comment

by:objects
ID: 23628241
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
 
LVL 61

Expert Comment

by:Kevin Cross
ID: 23632531
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
 
LVL 86

Expert Comment

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

Open in new window

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month13 days, 2 hours left to enroll

580 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question