Word counting program - new to strings

Im trying to write a program that will tell me how many times the word "rabbit" appears in a text file. This is what I ahve so far and I am not sure if it is correct. I get a cannot find symbol
symbol : method indexOf(java.lang.String) error when I compile.
import java.util.Scanner;       
import java.io.File;            
import java.lang.String;
public class Rabbitcount
  public static void main( String[] args ) throws Exception  // new: throws Exception, copy and paste for now
    File f = new File("rabbit.txt");
    Scanner input = new Scanner(f);
  while (true) {
  int x = indexOf("rabbit");
    System.out.println("There are " + x + " occurences of rabbit in the text.");
// Close the file
    input.close();  
} Any help is appreciated
Edited by: euchresucks on Nov 3, 2008 2:23 PM

indexOf() is a String method. If you were going to use that, you would have to load the file's contents into a String and call indexOf() on that String. You would also need to use the two-argument form of indexOf() so you could start each search at the point where the last match ended.
But you don't need to do any of that. You've already a perfectly good Scanner there; use it to do the searching. Hint: the name of method you need does not start with the word "next".

Similar Messages

  • Adapting My Word Counter Program to also Search and Replace

    Hi,
    I recently completed a word counter program for a school assignment. It reads in a file name from the command line and prints the contents to the screen before counting the number of words. i now want to try and adapt this program to also search for and replace a word specified by the user and print the document back to the creen with the changes. it would work something like this:
    java SearchReplaceApp test.txt
    This is a test
    This is a test
    This is a Test
    This is a Test
    This file contains 16 words
    Search for?: test
    Replace with?: Test
    This is a Test
    This is a Test
    This is a Test
    This is a Test
    Search for?:
    etc..........
    I was planning on using the replaceAll method and obviously i would neeed some kind of loop structure (probably a do/while loop) but i dont really know how to implement this in this scenario.
    Any suggestions would be appreciated. NEWBIE ALERT!!!!!! im afraid as i have very little programming experience, so please keep it as simple as possible please.
    maybe i'll give you a hug or something

    Just to make it easier for you guys to understand heres the code i have for my word counter, which i have now renamed SearchReplaceApp:
    import java.io.*;
    import java.util.*;
    class SearchReplaceApp
                public static InputStreamReader input =
                                       new InputStreamReader(System.in);
                public static BufferedReader keyboardInput =
                                       new BufferedReader(input);
                public static void main(String[] args) throws IOException
                                      FileReader file = new FileReader(args[0]);
                                      BufferedReader MyFile = new BufferedReader(file);
                                      StringTokenizer TokenizeMe;
                                                int NumberOfTokens = 0;
                                                int NumberOfWords = 0;
               TokenizeMe = new StringTokenizer(MyFile.readLine());
               NumberOfTokens = TokenizeMe.countTokens();
               while (NumberOfTokens != 0)
                                        for (int WordsInLine=1; WordsInLine<=NumberOfTokens;
                                                                        WordsInLine++)
                                                     System.out.print(TokenizeMe.nextToken()+" ");
                                        System.out.println();
                                        NumberOfWords += NumberOfTokens;
                                        String line = MyFile.readLine();
                                        if (line==null) break;
                                       TokenizeMe = new StringTokenizer(line);
                                       NumberOfTokens = TokenizeMe.countTokens();
                 System.out.println("\nThis file contains " + NumberOfWords + " words");
                 MyFile.close();
    }as you can see it does use a tokenizer, i would ideally like to be able to replace parts of words as well as whole words and also prompt for another search word after displaying the updated file e.g.
    This is a test
    Search for?: is
    Replace with?: was
    Thwas was a test
    Search for?:
    im really quite stuck on this so suggestions of any kind are welcome
    thanks

  • Word count program..twisting my mind

    Hi fellow Java lovers , i'm new on this forum and I had a little tricky java program. Apparently I have a piece of text , about 1500 words long (in french) and I need to come with a code that makes it possible:
    1.Load up the piece of text using a menu option , convert it to lower case and display it.
    2.Display average word length
    3.Display number of commas per 1000 words
    4.Display number of times the word "le" occurs per 1000 words. (tip: u will hav to search for space followed by "l" then "e"...> " le " otherwise java will pick it as part of a word)
    5.Allow a search to b done for any word and display number of times it occurs.
    Anyone wanna come to my rescue ?

    Try this:
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class CandyGirl1
         static class DisplayPanel
              extends JPanel
              private JTextArea mTextArea= new JTextArea();
              private JLabel mLabel= new JLabel(" ");
              public DisplayPanel()
                   mTextArea.setEditable(false);
                   setLayout(new BorderLayout(4,4));
                   add(new JScrollPane(mTextArea), BorderLayout.CENTER);
                   add(mLabel, BorderLayout.SOUTH);
              public Dimension getPreferredSize() {
                   return new Dimension(600, 480);
              public void setText(String text)
                   text= text.toLowerCase();
                   mTextArea.setText(text);
                   mLabel.setText(
                        "<html>" +
                        "Average word length: " +getAverage(text) +"<p>" +
                        "Commas per 1,000 words: " +getCommas(text) +"<p>" +
                        "Occurences of 'le': " +getOccurs(text, "le") +"<p>" +
                        "</html>");
              public void search(String what)
                   mLabel.setText(
                        "Occurences of '" +what +"' : " +getOccurs(mTextArea.getText(), what));
              private int getOccurs(String text, String what)
                   int count= 0;
                   StringTokenizer st= new StringTokenizer(text, " ");
                   while (st.hasMoreTokens()) {
                        if (st.nextToken().equals(what))
                             count++;
                   return count;
              private int getCommas(String text)
                   int i= 0;
                   int cnt= 0;
                   for (; i< text.length(); i++) {
                        if (text.charAt(i) == ',')
                             cnt++;
                   return (1000/text.length())*cnt;
              private int getAverage(String text)
                   int count= 0;
                   int length= 0;
                   StringTokenizer st= new StringTokenizer(text, " ");
                   while (st.hasMoreTokens()) {
                        length += st.nextToken().length();
                        count++;
                   return length/count;
         static class Application
              extends JFrame
              private DisplayPanel mDisplayPanel= new DisplayPanel();
              public Application()
                   getContentPane().add(mDisplayPanel);
                   JMenuBar bar= new JMenuBar();
                   setJMenuBar(bar);
                   JMenu menu= new JMenu("File");
                   menu.setMnemonic(KeyEvent.VK_F);
                   bar.add(menu);
                   JMenuItem item= new JMenuItem("Open");
                   item.setMnemonic(KeyEvent.VK_O);
                   menu.add(item);
                   item.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) { open(); } });
                   item= new JMenuItem("Search");
                   item.setMnemonic(KeyEvent.VK_S);
                   menu.add(item);
                   item.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) { search(); } });
              private void search()
                   String what= JOptionPane.showInputDialog(this, "Serach for:");
                   if (what != null)
                        mDisplayPanel.search(what);
              private void open()
                   JFileChooser chooser= new JFileChooser();
                   if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
                        open(chooser.getSelectedFile());
              private void open(File file)
                   try  {
                        FileReader reader= new FileReader(file);
                        StringBuffer str= new StringBuffer();
                        char[] buf= new char[128];
                        while (true) {
                             int read= reader.read(buf, 0, buf.length);
                             str.append(buf, 0, read);
                             if (read < buf.length)
                                  break;
                        mDisplayPanel.setText(str.toString());
                   catch (Exception e) {
         public static void main(String[] argv)
              Application frame= new Application();
              frame.pack();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
    }

  • Help with a Word Counting Program..

    I need some help with a program I am trying to write
    The program is being written in BlueJ.
    Im just starting the program and am completely confused on how I should write this...
    But here is what I have to do..
    I have to use a scanner to scan a Text file and count the # of Words the number of Vowels (including Y when it is) and the # of Palindromes (Word spelled same forward and Back) as well as which Palindromes are being used.
    It would be good to have a class to clean the text and a seperate class for the tasks...
    I do not want to use anything other than "If" statements and while loops (no "for" loops) and only use Printwriter as the output file writer.
    Thnx to anyone in advance

    I have a basic Vowel coding that doeswnt work...
    public class vowel{
    String word = "heyyou";
    String vowels = "aeiouy";
    int[] countv = new int[vowels.length()];
    int countv2;
    int i=0;
    if(i<word.length();) { i++ {
    if (int j=0 && j<vowels.length()) {
    return j++;
    if (word.charAt(i)==vowels.charAt(j)) {
    countV[j]++; countV2++;
    for (int i=0; i<vowels.length(); i++) {
    System.out.println("Vowel "vowels.charAt(i)" = "+vcnt);
    System.out.println("Consonants = "+(word.length()-vtot)); }
    I also have a basic Palindrome code that works as a boolean but I need to make it return what the palindromes are and how many of them are there. I wanna know how I would do this.
    public class Palindrome{
    public static boolean isPalindrome(String word) {
    int left = 0;
    int right = word.length() -1;
    while (left < right) {       
    if (word.charAt(left) != word.charAt(right)) {
    return false;
    left++;
    right--;
    return true;
    I would also like to know how to actually start writing the word counter.

  • I'm writing a word-count program

    I'm sure this question has come up often but I've searched the web and haven't found a straight-forward answer for my problem. I need to write out a program that simply counts the number of words in a file of text.
    This has to be done in two different ways:
    1)Using a string object where I input each line.
    2)Assuming the string class doesn't exist, and to input the data one character at a time.
    Now, I know you won't do the work for me, and I haven't been able to figure out any code to put in yet. I just could use a push in the right direction with this. I haven't been able to find any good examples of this type of programming.

    1)Using a string object where I input each line.You could [url http://javaalmanac.com/egs/java.io/ReadLinesFromFile.html]read the text file line by line.
    For each line you could [url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#split(java.lang.String)]split it using [url http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html#sum]the regular expression character for whitespace (zero or more times).
    The number elements of the returned array is is the word count for each line.
    2)Assuming the string class doesn't exist, and to input the data one character at a time.You could still read the text file in the same way as previously but instead of using the readLine() method
    you should use the [url http://java.sun.com/j2se/1.5.0/docs/api/java/io/BufferedReader.html#read()]read() method.
    Each time the returned byte is either ' ', '\t', '\f', '\r' or '\n' (and that the previous byte is not) you could increment the word counter.
    Regards

  • Word Count Discrepancy

    I am editing a document in Pages for iOS (iPad) but am getting a discrepancy in word count when compared to the same document in Word 2010. Both documents are unaltered from when I opened them (from an email), but Pages tells me it's 1,130 whereas Word is giving me 1,045. Any ideas why?

    Interesting Quesion:)
    In theory, the Character Count in Windows Explorer gets the same result as the Characters(no spaces) value in Word Count.
    However, the operational definitions of how to count the words can occur (namely, what "counts as" a word, and which words "don't count" toward the total) is similar but different. Different word counting programs may give varying results, depending
    on the text segmentation rule details, and on whether words outside the main text (such as footnotes, endnotes, or hidden text) are counted.
    In your story, the Character count in Windows Explorer(28877) is lower than the result in Word count (27286). It's difficult for me to figure out the root exactly duo to:
    the space (any of various whitespace characters, such as a "regular" word space, an em space, or a tab character)
    hyphen or a slash
    Asian/Non-Asian words.
    All of them above might be the factors in this case. Hope the info light you.
    Cheers,
    Tony Chen
    Forum Support
    Come back and mark the replies as answers if they help and unmark them if they provide no help.
    If you have any feedback on our support, please contact
    [email protected]

  • I recently updated to the OSX 10.8.3 Operating Sistem.  I am writing a book and now cannot open any word document I've created.  Could not find a newer version of the Microsoft Word Processing Program.  Is Pages the next thing? Can I recover my documents?

    I recently updated to the OSX 10.8.3 Operating Sistem.  I am writing a book and now cannot open any word document I've created with the old system.  Could not find a newer version of the Microsoft Word Processing Program.  Is Pages the next thing? Can I recover my documents?  How?

    I'm in the same boat: new to OS X and Mac, and in the middle of a book. I switched because I heard about the the ease of using Mac, but so far, for me, it's been a nightmare. I bought 2011 Office Mac and hate everything about it, the most recent being the inability to open or cut or paste any of my original word files. I understand that this could have easily been done with earlier versions, but not Mountain Lion (which I learned is what OSX is.) Since I work with language, I am amazed at the assumptions of the Apple community. It helps to use common language and explain even the basics.  
    So all the helpful hints to use the latest version of Office Mac are to no avail. Now what?

  • Word count and my ActionPerformed

    I am having a little trouble with my program and was wondering if anyone could spot the mistake... I am trying to make a simple application that will count the number of words in a text field via click of a button and display the results.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class WordCount extends JFrame implements ActionListener
    // added JTextPane, JScrollPane, JPanel JTextField, and JButton
        public static void main(String[] args)
         // layout
        public WordCount()
              super();
              Container cp = getContentPane();
              wordCount.setEditable(false);
              south.setLayout(new FlowLayout(FlowLayout.CENTER));
              south.add(jbtCount);
                   jbtCount.addActionListener (this);
              south.add(new JLabel("  Word Count: "));
              south.add(wordCount);
              cp.add(BorderLayout.CENTER,jsPane);
              cp.add(BorderLayout.SOUTH,south);
         public void actionPerformed(ActionEvent e)
              //if(e.getSource() == jbtCount)   // user clicks Count Words Button
              Object s = e.getSource();
             if ( s instanceof Button )
                  jtPane.setDocument(new DefaultStyledDocument() {
                        public void insertString(int offset, String str, AttributeSet as) throws BadLocationException
                           super.insertString(offset,str,as);
                           String text = jtPane.getText();
                           String[] tokens = text.split(" ");
                           wordCount.setText("" + countValid(tokens));
                         public void remove(int offset, int len) throws BadLocationException
                           super.remove(offset,len);
                           String text = jtPane.getText();
                           String[] tokens = text.split(" ");
                             wordCount.setText("" + countValid(tokens));
                  else{}
         } // end actionPerformed
         private int countValid(String[] tokens)
              int count = 0;
             for (int i = 0; i < tokens.length; i++)
                    if (tokens.trim().length() != 0)
              count++;
         return count;
    } // end public class WordCount

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class WordCount extends JFrame implements ActionListener
         JTextPane jtPane = new JTextPane();
         JScrollPane jsPane = new JScrollPane(jtPane);
         JPanel south = new JPanel();
         JTextField wordCount = new JTextField(20);
         JButton jbtCount = new JButton("Count Words");
        public static void main(String[] args)
              int width = 700;
              int height = 300;
               WordCount f = new WordCount();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             f.setSize(width, height);
             f.setTitle("Word Counter");
             f.setLocation(200, 200);
             f.setVisible(true);
        public WordCount()
              super();
              Container cp = getContentPane();
              wordCount.setEditable(false);
              south.setLayout(new FlowLayout(FlowLayout.CENTER));
              south.add(jbtCount);
                   jbtCount.addActionListener (this);
              south.add(new JLabel("  Word Count: "));
              south.add(wordCount);
              cp.add(BorderLayout.CENTER,jsPane);
              cp.add(BorderLayout.SOUTH,south);
         public void actionPerformed(ActionEvent e)
              //if(e.getSource() == jbtCount)   // user clicks Count Words Button
              Object s = e.getSource();
                  // *** process Button actions
            if ( s instanceof Button )
                  jtPane.setDocument(new DefaultStyledDocument() {
                        public void insertString(int offset, String str, AttributeSet as) throws BadLocationException
                           super.insertString(offset,str,as);
                           String text = jtPane.getText();
                           String[] tokens = text.split(" ");
                           wordCount.setText("" + countValid(tokens));
                         public void remove(int offset, int len) throws BadLocationException
                           super.remove(offset,len);
                           String text = jtPane.getText();
                           String[] tokens = text.split(" ");
                             wordCount.setText("" + countValid(tokens));
                  else{}
         }// end actionPerformed
         private int countValid(String[] tokens)
              int count = 0;
             for (int i = 0; i < tokens.length; i++)
                    if (tokens.trim().length() != 0)
              count++;
         return count;
    } // end public class WordCount

  • Trying to write Javascript code to get word count

    I copied code from an internet source and spent hours making adaptations so that my code would compile in Adobe Acrobat XI form Actions.
    Nothing I can do will make the script recognize that a character is a space. I need to count spaces so that I can count words.
    Finally I gave up and tried to use Replace to replace spaces with some other character that perhaps the program would recognize, but I can't get the Replace method to work either. Well, I can get it to work for the first instance of a space in the string, but not replace all spaces in the string. I have tried the "/text/g" convention and the "text,newtext,"All" convention. Do I really have to write another loop to replace the spaces individually?
    It seems so odd that there aren't more simple functions in Java (I'm new to Java) - it's like programming in machine language. And every function I investigate has more than one syntax I guess depending on what version Javascript you are using - and I can't even find out which version of Javascript Acrobat Pro XI is using!
    Following is my code - I will be doing something with the wordCount - this is just an initial snippet:
        var f = getField(event.target.name);
        var input = f.value;
        var wordCount = 0;
        if (input.trim.isEmpty){
            wordCount = 0;
        else {
            wordCount = 1;
        for (var i = 0; i < input.length; i++) {
            var ch = input.charAt(i);
            var str = new String("" + ch);
    //        if (i+1 != input.length) && (str == " ") && (!("" + input.charAt(i+1)) = " ")){
            if (i+1 != input.length && str === " " && "" + input.charAt(i+1) !== " "){
                wordCount++;
    app.alert (wordCount);

    See adracadabraPDF.net and the free utilities they offer. There is a word counter by page and document.
    The example from the Acrobat JS API Reference:
    Example
    Count the number of words in a document
    var cnt=0;
    for (var p = 0; p < this.numPages; p++)
    cnt += getPageNumWords(p);
    console.println("There are " + cnt + " words in this doc.");
    The above is for the content in a PDF.
    If you want to count the words in a form field, you need to determine how you want to split the field value and change certain white space characters to a given character like a space.
    You can use the "split()" method to convert  a field value to an array of items based on the "split" character.
    If your entry is just a line of text and does not have have any punctuation for string termination you can use
    var aWords = event.value.split(" ");
    console.println("Number of words: " + aWords.length;

  • Word Count Method?

    Hey all. I am having a bit of an issue. I need to write a program to read a file and count how many words are in the file. So far I have the basis for the while loop to read a line from the file, but I can't seem to figure out how to code the loop to count the words. Java doesn't have a word count method does it? I have looked, but have been unable to find anything of the sort.
    I don't want you do do this for me, I just need some helpful hint/tips. Anything you can provide is appreciated. Thanks!

    I am now having this problem. Here is a code segment:
    void count(String newFileName) throws IOException
              fileName = newFileName;
              FileRead file = new FileRead(fileName);
              wordCount = 0;
              StringTokenizer st = new StringTokenizer(fileName);
              while (file.getLine() != null)
                 while ( st.hasMoreTokens() )
                    st.nextToken();
                    wordCount++;
         }I think it should be changed to StringTokenizer st = new StringTokenizer(file) but when I do so, I get the error "The constructor StringTokenizer(FileRead) is undefined". I assume this is because file is an object not a String variable. the current code has a problem because it only returns 1. Any ideas?
    Edited by: zcrane on Nov 1, 2007 3:40 PM

  • Word count application

    Hi am attempting a previous exam question and would appreciate some advice:
    I have been given a class that has been partly implemented. The class called Document
    that determines how many words are in the document, and how many certain specified
    words are in the document. That is, there is a TotalWordCount and a GetWordCount method
    which determines these.
    The second class is a test class for the Document class (see below).
    My questions are, what would be appropriate code for the constructor? I am assuming I only need
    to pass the name of the file (which the constructor already does?) What would a suitable means to count the number of words? I am unsure how to count individual specified words. (I have implemented a simply word count class that only counts ALL words).
    Lastly, does my Document tester class appear to be correct? (in context to the Document class).
    Any help/advice sincerely appreciated!
    Regards,
    Benjamin.
    import java.io.*;
    import java.util.*;
    public class Document extends File{
         private int totalWordCount = 0;
         public Document (String filename){
              super(filename);
         //constructor code goes here
         public int getWordCount () {
         return totalWordCount;
         public int getWordCount (String[] words){
              return countWords(this.getName(), words);
         private int countWords (String filename, String[] words) {
              String line, token;
              StringTokenizer tokenizer;
              int wordCount = 0;
              //create the procedure for counting the words;
         return(wordCount);
    import java.io.*;
    import java.util.*;
    public class DocumentTest{
         public static void main(String[] args){
              String filename = "myfile.txt";
              Document myDoc;
              myDoc = new Document();
              system.out.println(myDoc.getWordCount);
              system.out.println(myDoc.getWordCount("a");
              system.out.println(myDoc.getWordCount("and");
              system.out.println(myDoc.getWordCount("the");
              system.out.println(filename);
              //Create a new document
              //print out a total word count
              //print out the number of times the words "a", "and" or "the"
              //appear in the file
              //Print out the Documents name using myDoc
              try{
              FileReader fr = new FileReader(filename);
              BufferedReader inFile = new BufferedReader(filename);
    }

    Yeah its a bit messy, there was nothing wrong with 'extends File' and the call to super(string) per se, its just a bit untidy as, even though it takes the String path/name in the constructor, it makes the code less readable IMO.
    You might be better off with something more along the lines of this - its a suggestion and neither is it complete;-import java.io.*;
    import java.util.*;
    class MyDocumentCounter{
       private int totalWordCount = 0;
       File file;
       String fileName;
       String fileString;
       int wordsInFile;
       public MyDocumentCounter (String fileName){
          this.file = new File(fileName);
          this.fileName = fileName;
          this.fileString = readNewFile(file);
          this.wordsInFile = setWordCount(fileString)
          setWordCount(fileString);
       private String readNewFile(File file){
          StringBuffer sb = new StringBuffer();
          try{
             BufferedReader buf = new BufferedReader(new FileReader(file));
             String text;
             while ( (text = buf.readLine()) != null) sb.append(text);
             buf.close();
          }catch(IOException ioe) { ioe.getMessage(); }
          return sb.toString();
       public int setWordCount(String fileString) {
          StringTokenizer tkn = new StringTokenizer(" \n",fileString);
          return tkn.countTokens();
       public int getWordCount(){
          return wordsInFile;
       public int countThisWord(String word) {
         return counter;
    }I'll leave you to figure out the countThisWord() method. And java.io.File has a very useful method;-
    myFileName.exists() which returns a boolean

  • Word count question

    Hi,
    I have a file which contains some words.
    I have to read the file and calculate each word and print the total beside the word
    for example abc= 1+2+1 =3
    where a=1,b=2,c=3,d=4 ...........y=25,z=26.
    could some one please help me to solve the problem.
    Any help is appreciated.

    Firstly, you may want to go to the java tutorial. This provides a lot of good, hands-on information on how to program in Java. You can find that tutorial on
    http://java.sun.com/docs/books/tutorial/
    There is a section that gives information on i/o. Look at
    http://java.sun.com/docs/books/tutorial/essential/io/bytestreams.html
    for an example.
    The information you provided may be inaccurate - you said:
    for example abc= 1+2+1 =3
    where a=1,b=2,c=3,d=4 ...........y=25,z=26.which seems to make little sense (sorry to be so nitpicking). What I think was meant is:
    for example abc= 1+2+3 =6
    where a=1,b=2,c=3,d=4 ...........y=25,z=26.With that in mind, I would suggest the following strategy as to finding the solution:
    1. Split the problem into small sub problems and solve these sytematically:
    1.1. How to read a file
    Action:
    1.1.1. Create an example text file
    1.1.2. Write a program that reads the file and prints it's content onto the console.
    1.2. How to extract words from a string.
    Action: Write a program that reads a string, splits it into words and prints each word
    on a new line
    1.3. How to extract the characters from a word
    Action: Modify the program you wrote in step 1.2. so that it splits each extracted word into its characters and prints each character onto a new line.
    1.4. How to find the number to a character
    Action: Modify the program from step 1.3., so that instead of the characters it now prints the corresponding numerical value of each character onto a new line.
    2. With these steps you have the basic building blocks for your program. You need to combine the knowledge you aquired and create the final program.
    If you arrived here, you are not far away from your solution!
    This actually describes a method on how to tackle complex problems. You employ a divide-and-conquer technique:
    a. Split a problem into smaller sub problems (as much as possible)
    b. Tackle each problem separately, creating solutions for each sub problem.
    c. Combine the solutions to the sub problems and apply them to the whole problem.
    The skill is in finding out how to divide the problem at hand. The side effect of this technique is that it aids re-use: Later you may find that some sub problems reoccur in other projects - you could then reapply the solutions you found for those sub problems. Therefore it's wise to keep a record of your solutions; you build a toolbox that way which you can use!
    Hope this helps!

  • Array words count

    Hi guys
    This code is giving me this output
    The New York Times is an American daily newspaper founded and continuously published in New York City since September 18 1851 It has won 112 Pulitzer Prizes more than any other news organization 0
    I need to read and split the array (I believe that part works)
    I also need to count the words and display it like this
    The(1)  New(2) York(2) Times(1) is (1) ...etc
    I am   System.out.print(token + " "  ) ; then I need to count the words and display the number in front
    Thank you
    package test4;
    import java.util.StringTokenizer;
    * @author rechever
    public class Test4 {
         * @param args the command line arguments
        public static void main (String[] args) {
           System.out.println("Displaying a paragraph: ”): ");
                String sentence1 = "The New York Times is an American daily newspaper, founded and continuously published "
                        + "in New York City since September 18, 1851. It has won 112 Pulitzer Prizes, more than any other news organization";
        //        String sentence1  = scanner.nextLine();
          /* regular expression   */
          sentence1 = sentence1.replaceAll("\\,"," ");
          sentence1 = sentence1.replaceAll("\\."," ");
          sentence1 = sentence1.replaceAll("\\;"," ");
                StringTokenizer stt = new StringTokenizer(sentence1," ");
              // int countWords = 1;  
                while
                    (stt.hasMoreTokens()){
                    String token = stt.nextToken();
                   System.out.print(token + " "  ) ;
                 // String  value = sentence1;
                 //  String value = token;
              //  insertNode(value);
              //  insertNode(value);
                for(int countWords = 0; countWords < sentence1.length(); countWords++ ) {
           if(sentence1.isEmpty()) {
             System.out.println(countWords);
                } // end of Main  

    Believe I try before I ask, if you see the code I was able to split the array, I am having problems with the counts and displaying the results in front of the words..
    as you can see I initiated the loop, I just can not get it to work...
    for(int countWords = 0; countWords < sentence1.length(); countWords++ ) {
           if(sentence1.isEmpty()) {
             System.out.println(countWords);
                } // end of Main 
    I need to able to split the array
    StringTokenizer stt = new StringTokenizer(sentence1," ");
              // int countWords = 1;  
                while
                    (stt.hasMoreTokens()){
                    String token = stt.nextToken();
                   System.out.print(token + " "  ) ;
    then after the array split I need to counts the words,
    this 
    for(int countWords = 0; countWords < sentence1.length(); countWords++ ) {
           if(sentence1.isEmpty()) {
             System.out.println(countWords);
    is not doing the trick..
    I am in the business of learning, I am not looking for a free ride...I google it, I look in books
    This code is doing it but I have to call a method to insert the array in a Binary tree
    something like tree.insertNode (value)
    being value the data stoom the split array....
    Now if you want to give some ideas (a link, documentation anything of how to call a method from  a class that is using maps...that will be great
    I though that doing it in a simple array was easy... again, I just learning
    Thank you
    import java.io.PrintStream;
    import java.util.*;
    public class WordTypeCount
       public static void main( String[] args )
          // create HashMap to store String keys and Integer values
          Map< String, Integer > myMap = new HashMap< String, Integer >();
          createMap( myMap ); // create map based on user input
          displayMap( myMap ); // display map content
       } // end main
       // create map from user input
       private static void createMap( Map< String, Integer > map )
          Scanner scanner = new Scanner( System.in ); // create scanner
          System.out.println( "Please Enter the sentence from the the from Edgar Allen Poe’s “Fall of the House of Usher”):" ); // prompt for user input
          String input = scanner.nextLine();
          // tokenize the input
          String[] tokens = input.split( " ");
          // processing input text
          for ( String token : tokens )
             String word = token.toString(); 
                     ///toLowerCase(); // get lowercase word
             // if the map contains the word
             if ( map.containsKey( word ) ) // is word in map
                int count = map.get( word ); // get current count
                map.put( word, count + 1 ); // increment count
             } // end if
             else
                map.put( word, 1 ); // add new word with a count of 1 to map
          } // end for
       } // end method createMap
       // display map content
       private static void displayMap( Map< String, Integer > map )
          Set< String > keys = map.keySet(); // get keys
          // sort keys
          TreeSet< String > sortedKeys = new TreeSet<  >( keys );
          System.out.println( "\nMap contains:\nKey\t\tValue");
          // generate output for each key in map
          for ( String key : sortedKeys )
          // System.out.printf( "%-10s%10s\n", key, map.get( key ) );
          System.out.printf( "%-5s%-5s", key,map.get( key ) );
         // System.out.printf("\nsize: %d\nisEmpty: %b\n", key, map.get( key ) );
          System.out.printf(
             "\nsize: %d\nisEmpty: %b\n", map.size(), map.isEmpty() );
       } // end method displayMap
    } // end class WordTypeCount
    Thank you

  • Word Count?? Anywhere? Please?!

    I just recently switched from Windows to Mac. I love this new word processing program, but I can't seem to find one key tool that Microsoft Word has - the word counter!! Does Pages have a word counter?? Please help, I need this for school! Thanks everyone:)
    Also, does anyone know how to change your alias on this discussions board? The name I chose was a bit impulsive, and I'd like to go with a different one if possible! Thanks again~
    <3D

    Welcome to Apple Discussions, Weezy's Deezy!
    Does Pages have a word counter??
    Yes, see this thread:
    http://discussions.apple.com/click.jspa?searchID=7127794&messageID=6520088
    Also, does anyone know how to change your alias on this discussions board?
    It is not possible. Apple has chosen to lock you in to a single alias. If you want to use a different one, stop using this account and set up a new one. Sorry.

  • TextEdit Word Count?

    Hi folks, I'm relatively new to Apple. (New enough to not know the proper forum for this question, though). Can I do a word count in TextEdit? If so, how? Any help is greatly appreciated.

    Here is the applescript to tell you the word count:
    tell application "TextEdit"
    set WordCount to the number of words in the the front document
    display dialog "The wordcount is: " & WordCount
    end tell
    What you need to do to install this is this:
    Run the program called "Scripteditor", which you can find somewhere in the programs directory - there is no point in my trying to tell you where as my system is set up in Foreignspeak. You'll have to run a search, which thankfully is very easy!
    To make a new script press apple-n, then copy and paste the text I gave above into the window that appears. Then run the script and it will tell you how many words there are in your current TextEdit file.
    There is probably a neater way of running the script than opening ScriptEditor, but given that I have been playing with this stuff for only a very short period of time I don't know about it yet.
    Best Wishes, Max
    p.s. My favourite script of the moment, which speaks whatever I type:
    set toSay to "I would like a cup of tea."
    repeat
    set toSay to the text returned of (display dialog "Max doeth speak:" default answer toSay)
    say toSay
    end repeat
    (childish, I know!)
      Mac OS X (10.4.3)  

Maybe you are looking for

  • Please send tables used for this report.

    hi pls any one send all the tables names are used in this given report report: <b>Created report that display month-wise sales details by comparing with previous month and yearly sales details with selection criteria based on date.</b> thanks in adva

  • How to configure RMAN - Oracle EBS R12

    Hi, I have installed Oracle EBS R12 on OEL 5.6 and want to configure Backup strategy for Database. Database Version is 11.1.0.7. Currently Database is in Noarchivelog mode and want to take backup of database using RMAN. Can anyone guide me what are t

  • Subscribe doesn't work

    Hi, I've published my iWeb site ( http://www.thedownlowconcept.com ) to an external server and My subcribe button on my blog ( http://www.thedownlowconcept.com/DOWNLOWBlog/DOWNLOWBlog.html ) isn't working. I entered the URL ( http://www.thedownlowcon

  • HTTPS + T3. Is it possible?

    Hi All, This is a question rather for "Weblogic - Security" space, but I have no rights to start discussion there. WLS 12.1.2 To meet the requirement "Switch to HTTPS, but leave t3" the following steps are performed in admin console for managed serve

  • Failed download error message and missing patch message, why?

    For the last couple of days I've been trying to download premiere pro cc and the first time I got a message saying  'missing patch' and I needed to update. I clicked on the update but it kept failing. SO, I uninstalled premiere and adobe cloud and tr