Solved

Simple Letter Counter Debugging

Posted on 2008-10-29
2
852 Views
Last Modified: 2010-04-21
Greetings, I'm trying to write a program that counts the letters in sentence. the catch is i want it to be able to take in a paragraph and display the output for every sentence in the paragraph... someone in this jumbled web of code im having a run time error and cant for the life of me get it straight... can someone here please help me straighten this out so i dont have to go threw and restructure the rest of my program to work around this...

Sincerely, Danielcc
/**
 

 * 
 

 */
 

import javax.swing.*;
 

/**
 

 * @author danielcc

 *
 

 */
 

public class LetterCounterSecond {
 
 
 

	
 

	
 

//this counts the periods
 

public static int countPeriods(String input){
 

	int numbOfPeriods=0;
 

	for(int index=0 ; index < input.length() ; index++){
 

		if (input.charAt(index)=='.'){
 

			numbOfPeriods++;
 

		}
 

	}
 

	return numbOfPeriods;
 

}//end of period counter
 
 
 
 
 

//this is the length of the paragraph
 

public static int lengthOfParagraph(String input){
 

	int length=input.length();
 

	return length;
 

}//end lengthOfParagraph
 
 
 

//this makes an array out of the paragraph for probing
 

public static char[] parragraphArray(String aInput){
 

 	String input=aInput.toLowerCase();
 

	char[] parragraphArray=new char[lengthOfParagraph(input)];
 

	for(int index=0;index<lengthOfParagraph(input);index++){
 

		parragraphArray[index]=input.charAt(index);
 

	}
 

	return parragraphArray;
 

}//end of parragraphArray
 
 
 
 
 
 
 

//this takes the indexes of the periods in the paragraph starting at the first period
 

//array will look like this [0,5,10,25]... note the 0 as a place holder used later 

//to mark the begging of first sentence by substrings
 

public static int[] indexOfPerriods(String input){
 

	int[] indexOfPeriods=new int[countPeriods(input)];
 

	for(int index=0; index<countPeriods(input); index++){
 

		//must use i because index is taken
 

		char[] parragraphArray= parragraphArray(input);
 

		indexOfPeriods[0]=0;
 

		if(parragraphArray[index]=='.'){
 

			for(int i=1; i<(countPeriods(input)+1);i++){ 
 

					if(indexOfPeriods[i]==0){
 

						indexOfPeriods[i]=index;
 

					}
 

			}
 

		}
 

	}
 

	return indexOfPeriods;
 

}//end of indexOfPeriods
 
 
 
 
 

public static String[] arrayOfSentences(String input){
 

	int[] indexOfPeriods=indexOfPerriods(input);//note 0 is 0 and periods start on 1
 

	//declairing the array to hold arrays...
 

	String[] sentenceArray=new String[countPeriods(input)];
 

	//note this first for statement is new code and should be looked over
 

	for(int counter=0;counter<indexOfPeriods.length;counter++){
 

		for(int index=0;index<sentenceArray.length;index++){
 

			sentenceArray[counter]=input.substring(indexOfPeriods[index],indexOfPeriods[index+1]);
 

		}//end of for statement using array length

	}//end of first for statement using counter in conjunction with # of periods aka length of period array
 

	return sentenceArray;
 

}//end of arrayOfSentences
 

		
 
 
 

public static int[] letterTally(String input, int sentence){//sentence starts at 0
 

	
 

	int[] periodIndex=indexOfPerriods(input);
 

	
 

	for(int i=0; i<periodIndex.length; i++){
 

		System.out.println("LetterCounterSecond.letterTally: periodIndex["+i+"] is: " + periodIndex[i]);
 

	}
 

	
 

	input=input.substring(periodIndex[sentence],periodIndex[(sentence+1)]);//changed this from sentence,sentence++
 

	//String[] arrayOfSentences=arrayOfSentences(input);
 

	char[] inputArray=new char[input.length()];
 

		for(int index=0;index<input.length();index++){
 

			inputArray[index]=input.charAt(index);
 

			}	
 

	//this is a corresponding array for letters with 0 as a and equal to 0 1 is b and equal to one and so forth
 

	int[] letterCountArray= new int[25];
 

		
 

	for(int index=0;index<inputArray.length;index++){	
 

			//could use switch but a for loop would not require typing out long case scenarios		

			//switch(inputArray[index]){//letterArray is the letters with corresponding numbers ie 0 is a
 

			for(int i=0; i<26 ; i++){
 

				if (inputArray[index]==i){ 
 

					letterCountArray[index]=letterCountArray[index];//note letterCountArray is equal to the number of letter per the corresponding letterArray
 

				}
 

			}//end of for statement
 

		}//end of switch
 

	return letterCountArray;
 

}//end of letterTally
 
 
 

//this basicly brings everything together and prints the output	
 

public static void printResults(String input){
 

	for(int sentence=0;sentence<countPeriods(input);sentence++){
 

		int[] letterCountArray=letterTally(input,sentence);
 

		JOptionPane.showMessageDialog(null, "sentence: "+(sentence+1));
 

		JOptionPane.showMessageDialog(null, "a: "+letterCountArray[0]+"\nb: "+letterCountArray[1]+"c: "+letterCountArray[2]+
 

				"\nd: "+letterCountArray[3]+"e: "+letterCountArray[4]+"\nf: "+letterCountArray[5]+"g: "+letterCountArray[6]+
 

				"\nh: "+letterCountArray[7]+"i: "+letterCountArray[8]+"\nj: "+letterCountArray[9]+"k: "+letterCountArray[10]+
 

				"\nl: "+letterCountArray[11]);
 

		JOptionPane.showMessageDialog(null,"m: "+letterCountArray[12]+"\nn: "+letterCountArray[13]+"o: "+letterCountArray[14]+"\np: "
 

				+letterCountArray[15]+"q: "+letterCountArray[16]+"\nr: "+letterCountArray[17]+"\ns: "+letterCountArray[18]+"\nt: "+
 

				letterCountArray[19]+"u: "+letterCountArray[20]+"\nv: "+letterCountArray[21]+"w: "+letterCountArray[22]+"\nx: "+
 

				letterCountArray[23]+"y: "+letterCountArray[24]+"\nz: "+letterCountArray[25]);
 

	}
 

	
 

}	
 

	
 

	
 

	
 

	
 

	
 

	
 

	public static void main(String[] args) {
 

		// TODO Auto-generated method stub
 

	//asks for input and plugges into the printResults method	
 

	 String	input=JOptionPane.showInputDialog("Welcome please input a sentence!!!");
 

	 printResults(input);
 

	}
 
 
 

}

Open in new window

0
Comment
Question by:danielcc
2 Comments
 
LVL 1

Accepted Solution

by:
brunovinicius earned 125 total points
ID: 22837797
Hello,

I'm sure you are only beginning the program, right?
If I didn't misunderstood you, your objective is to split an text into sentences (delimited by dots) and then count the number of letters on each sentence. I've looked your code and just realized it got a large number of little mistakes that lead it to malfunction.

Here are some tips:
   1. Never skip thinking! You got to know what you want to do before writing the very first line of code.
   2. Try to split the problem in smaller parts ( in the one you mentioned, "Split the text into sentences" & "Count letters for each sentence" were clearly smaller parts of the main problem)
   3. Keep it simple. The simpler code is always the better (Note that simpler and smaller are different things). Of course there will be codes that are complex by the nature of the problem they solve.

That said, I written the two methods for tokinize the text and count strings.
Anyway I recommend you to try the thing again from the beginning, making sure every single method works fine, before moving to the next one.

Best Regards,
Bruno Vinicius

/**

 * This method will tokenize the text in various sentences. Only '.' is

 * considered as sentence delimiter. A maximum of 10 sentences are allowed.

 * 

 * @param text

 *            The text to tokenize.

 * @return An array list of the sentences

 */

public ArrayList<String> sentenceTokenizer(String text) {
 

    StringBuilder builder = new StringBuilder(text);

    ArrayList<String> list = new ArrayList<String>();
 

    // tokenizes the text into sentences (only '.' considered)

    while (builder.length() != 0) {

        // asks for the next '.' index

        int idx = builder.indexOf(".");
 

        // if an '.' wasn't found, consider the remaining text

        // to be the final sentence

        if (idx == -1) {

            idx = builder.length();

        }
 

        // removes the sentence from the builder

        String sentence = builder.delete(0, idx).toString();
 

        // adds it into the ArrayList

        list.add(sentence);

    }
 

    return list;

}
 

/**

 * Counts how many letters are on a sentence.

 * 

 * @param sentence

 *            The sentence to analyze

 * @return The letters count on the given sentence

 */

public int letterCount(String sentence) {
 

    int counter = 0;
 

    // scans the string looking if each char is a letter

    for (int i = 0; i < sentence.length(); i++) {

        // gets the next char

        char c = sentence.charAt(i);
 

        // asks Character class if it is a letter

        if (Character.isLetter(c)) {

            // if so, increment the counter

            counter++;

        }

    }
 

    return counter;

}

    

Open in new window

0
 
LVL 4

Author Closing Comment

by:danielcc
ID: 31511516
thanks man...
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Sorting in Excel with Group Headers if the Exist 2 82
How does Google get such fast response times? 5 151
Hide vba in gp 7 82
Apps blocked by Java 9 60
Iteration: Iteration is repetition of a process. A student who goes to school repeats the process of going to school everyday until graduation. We go to grocery store at least once or twice a month to buy products. We repeat this process every mont…
Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

911 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now