Frequency of words in Arrays

Dear Java Folks,
I still need your help!
I am still having problem after succeeding in tokenizing the Strings in LinkedList.
What I wanted to do is to find the Frequency of words or characters in an Array.
E.g
1�A,C,F,G,A
2�Baby,H,K,A,C,K
3�Oslo,S,F,T,K
The first line will return 2A, 1C, 1F, 1G. Thereafter, I will find the Frequency of the second line which will be 1Baby, 1H, 2K, 1A, 1C etc.
For now, I am only interested in getting the Frequency
of the first line.
My Code
public String DataCall() {
          DataInputStream dis = null;
          String line = null;
          String []words;
          String []Lines;
          List <String>result = new LinkedList<String>();
          List<String> dataList1 = new LinkedList<String>();
          List<String> dataList2 = new LinkedList<String>();
          List<String> onlyWords = new LinkedList<String>();
          List<Integer> frequency = new LinkedList<Integer>();
          int counter = 0;
          try {
                   File data = new File("C:/text.txt");
                    FileInputStream in = new FileInputStream(data);
                    dis = new DataInputStream (in);
                    BufferedReader br = new BufferedReader(new InputStreamReader(dis));
                    line  = br.readLine();
          if (line != null) {
                         Lines = (line.split(" ")); //Split the first row or line
                         for(String datas : Lines)  // add the data to the Linkedlist
                              dataList1.add(datas);
                         for (int i = 0; i < dataList1.size(); i++) {
                           words = (dataList1.get(i).split("�"));   // split to get to �
                           for (int b = 0; b < words.length; b++) {
                                String []wordCount = words.split(","); // split the remaing words or characaters
               for (String saveD : wordCount)
                         onlyWords.add(saveD); // add the data to Linkedlist "onlyWords
          // Start the frequency calculation
          for (int point = 0; point < onlyWords.size(); point++)
               if (!dataList2.contains(onlyWords.get(point))) //Initially dataList2 is empty here
                    dataList2.add(onlyWords.get(point)); // add data to Linkedlist "datalist2"
                    frequency.add(1); // add 1 to (int) Linkedlist "frequency"
               else
                    int tmp = 0;
                    tmp = onlyWords.indexOf(point); //get the index where the "word" occured first
                    counter = frequency.get(tmp); //ge the value of the same index in the Linkedlist "frequency"
                    counter++;
                    frequency.set(tmp, counter);
          for (int k = 1; k < dataList2.size(); k++) {
     System.out.println(onlyWords.get(k) + " " + frequency.get(k));
          else System.out.println("There is no data to read\n");
          catch (IOException e) {
                    //catch io errors
                    System.out.println("IOException error: " + e.getMessage());
          finally {
                    // if the file successfully opened
                    if (dis != null) {
                         try {
                         dis.close();
                         catch (IOException ioe){
                         System.out.println("IOException error when trying to close the file: " + ioe.getMessage());
               }//end if
          }// end finally
               return null; // just for a test. I will return result
     } // end DataCall
The code if run shows the the following the errors;
at java.util.LinkedList.entry(Unknown Source)
at java.util.LinkedList.get(Unknown Source)
at fileReader.DataFrequency.DataCall(DataFrequency.java:80)

here i have modified the code, but still getting the error in the count
import java.io.File;
import java.util.Formatter;
import java.util.Scanner;
public class StudentPoll_dasariHaritha {
private Scanner x;
int[] frequency = new int[5];
int count =0;
public void openFile(){
try{
x = new Scanner(new File("numbers.txt"));
catch(Exception e){
System.out.printf("No File found");
public void readFile(){
while(x.hasNext()){
int a= x.nextInt();
if(a==1){
frequency[0]=0;
++frequency[0];
break;
else if (a== 2){
frequency[1]=0;
++frequency[1];
break;
else if( a==3){
frequency[2]=0;
++frequency[2];
break;
else if (a==4){
frequency[3]=0;
++frequency[3];
break;
else if (a== 5){
frequency[4]=0;
++frequency [4];
break;
System.out.printf("%s%10s\n","Rating","Frequency");
System.out.printf("%s%10s\n","1",++frequency[0]);
System.out.printf("%s%10s\n","2",++frequency[1]);
System.out.printf("%s%10s\n","3",++frequency[2]);
System.out.printf("%s%10s\n","4",++frequency[3]);
System.out.printf("%s%10s\n","5",++frequency[4]);
public void closeFile(){
x.close();
in the main method iam calling these methods
StudentPoll_dasariHaritha read = new StudentPoll_dasariHaritha();
read.openFile();
read.readFile();
read.closeFile();
i think in the while loop iam making a mistake. can someone help me in rectifying it.

Similar Messages

  • Frequency Control Word (PXI-5402): Rounded up or down?

    A further question wrt PXI-5402 standard function generation.
    The frequency control word is calculated by dividing the desired output frequency by the sample clock frequency (100MHz for a PXI-5402) and multiplying it by 2^N where 'N' is the width of the DDS accumulator (48 for the PXI-5402). As the frequency control word is an integer does any fractional residual result in the control word being rounded up or rounded down?
    e.g. if a I request a frequency of 1Hz I get a control word of 2814749.767 which would give an actual output frequency of 0.99999997 Hz if rounding down or 1.00000008 Hz if rounding up.
    Thanks.

    I believe the FCW gets rounded. I actually was able to find a LV demo for you, but it was made for the 5411. You would need to change some values to make it work for the 5402/5406: http://www.ni.com/example/28757/en/
    Keep in mind that all of the DDS calculations are actually implemented in HW on an FPGA, see figure 2: http://www.ni.com/white-paper/5516/en/. The tuning word here is the same as the FCW. This image used to be used on that white paper before it was updated. The adder in Figure 2 is the same adder in this image below.
    Also, as I have mentioned before, the accuracy for the Sample Clock above for the 5402 is 25ppm. If the actual frequency you are generating is such a concern, are you using an external high accuracy clock source? What is your application?
    Product Support Engineer
    National Instruments

  • Finding offending bash completion 'bash: words: bad array subscript'

    Hey guys,
    I've recently started getting the error "bash: words: bad array subscript" on my console when hitting tab without having typed anything yet.
    Any idea how I can figure out what the offending bash_completion script is?
    Thanks,

    Maybe the same as this?
    https://bugs.launchpad.net/ubuntu/+sour … ug/1289597

  • Data Collection to Word Report array indexing

    Hi guys,
    Just need a bit of help deciding if I am measuring what i'm supposed to be. I'm trying to write the code for an automated collection of results, before i get the equipment to do it.
    Basically, I will have 3 voltages going into analog inputs and one digital input going into my DAQ.
    Two of the analog inputs need a single voltage recorded every minute for a hour. (at the minute i think my code samples one voltage every half second for 5 seconds, but i can easily change the timings of the loop) 
    Does the array indexing i'm using seperate the voltages read from each channel -  ie does the top index array (index 0) read the voltage from aI0? 
    By enabling indexing at the edge of the for loop i think i'm passing the single voltage (from each channel) read every loop iteration into the report graph, am i?
    Any help would be most appreciated
    Thanks,
    Christian
    p.s. This thread contains the whole problem i am trying to solve: http://forums.ni.com/t5/LabVIEW/Multiple-analog-inputs-performing-different-tasks/m-p/1163471#M50845...
    p.s. I realise i have posted this question in another thread already, but i did that by mistake!
    "If anyone needs me, I'll be in the Angry Dome!"
    Attachments:
    DAQ to report.vi ‏183 KB

    Hi,
    The task description is very confusing.
    - Why you use update mode Delete All? -- Why not delete uploaded data or Overwrite? -- incoming data are already discriminating by the cons unit, where is overlapping?
    - Why you need to add a new characteristic to the selection of target like company? You have a ConsUnit, an Investee unit etc. Why a new char?

  • Check variable against an array of words

    Hi,
    I wish to check a variable for a number of words that are in
    a array.
    Not sure if this is the best way to do it, but this is what i
    have.
    I have my own counter system that counts every visitor, but
    some of these visits are from BOTS, spiders..
    So i wish to have a method of searching the HTTP_USER_AGENT
    for certain words i put in a array.
    What i am after is how i get the words in an array and how i
    then get the script to check the HTTP_USER_AGENT for a word in the
    array and if so it will not complete the script. (not add to the
    counter)
    if none of the words are in the HTTP_USER_AGENT then it will
    add to the counter.
    so something like?
    <?
    // do array
    // check if HTTP_USER_AGENT contains a word from array
    if () {
    // increase counter if none of the words are in
    HTTP_USER_AGENT
    include(increase.php);
    ?>
    its the bit between the if () that i have no idea about, any
    help would be great.
    cheers in advance for your help.
    Jason

    not very clever wrote:
    > this is a bit more about what i am trying to do.
    >
    > <?
    > // do array
    > array(1)="something";
    > array(2)="something else";
    > array(3)=..
    > ..
    > ..
    >
    >
    > $HTTP_USER_AGENT = contants of the HTTP_USER_AGENT
    > // check if HTTP_USER_AGENT contains a word from array
    > if (array(x) is in the string $HTTP_USER_AGENT) {
    > // increase counter if none of the words are in
    HTTP_USER_AGENT
    > include(increase.php);
    > }
    >
    > ?>
    >
    >
    $myArray = array('blip','blop','glup',...);
    $counter = 0;
    foreach($myArray as $mA){
    if(preg_match('/'.$mA.'/',$HTTP_USER_AGENT)){
    $counter++;
    seb ( [email protected])
    http://webtrans1.com | high-end web
    design
    Downloads: Slide Show, Directory Browser, Mailing List

  • Error -200685 DAQmx Write Counter Frequency

    I have to generate 4 finite pulse trains with Counter Output and a X-series board (NI PCIe-6321). I know that with X-series boards only one counter is used to generate finite pulse train. I use LabVIEW 2010 sp1 and DAQmx 9.3.5.
    One task for each counter is created.
    When only one task runs, everything is ok, but, when more than one task runs, i receive "error -200685: Pulse frequency specified is not supported for this device given the Counter Timebase Rate." from DAQmx Write Counter Frequency. Error reports invalid data&colon; 0,000000
    I have checked data supplied and no zero frequency is passed to the VI. In fact, counter frequencies lower than 100 are forced to be 100 through a previous VI.
    Thanks for the help
    Attachments:
    Error.PNG ‏42 KB
    Zero frequencies avoided.PNG ‏7 KB

    OriginalP ha scritto:
     I payed attention to write non null frequencies and this is why this error sounds so strange to me.
    My last words... i found that two null frequencies (1018 and 1019 array indexes) were passed to Counter Output (see attached images "Counter Output Front Panel Data.PNG" and "Counter Output Block Diagram Data.PNG").
    It's quite strange, because VIs generating pulse train frequency data don't output these two null frequencies (see attached image "Array Output Data.png").
    This pair of null frequencies is random, but definetively the error is not in Counter Output DAQmx Write VI.
    Attachments:
    Counter Output Front Panel Data.png ‏33 KB
    Counter Output Block Diagram Data.PNG ‏21 KB
    Array Output Data.png ‏21 KB

  • Pass array to oracle stored procedure

    I have such a problem: I have to pass array to stored procedure, so I declare type:
    create type tNumberArray as table of number
    and create procedure:
    create or replace procedure proc_1 (in_param in tNumberArray) as
    .... BODY OF PROCEDURE ...
    when I call this procedure from C# like this:
    int []pParam = new int[3] {1,2,3};
    OracleCommand cmd = new OracleCommand("proc_1", dbConn);
    cmd.CommandType = CommandType.StoredProcedure;
    OracleParameter param14 = new OracleParameter("param", OracleDbType.Decimal);
    param14.Value = pParam;
    param14.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
    param14.Size = 3;
    param14.Direction = ParameterDirection.Input;
    cmd.Parameters.Add(param14);
    cmd.ExecuteNonQuery();
    an error occures. It say that there invalid number or type of parameters.
    But when I declare both type and procedure in a package everything goes fine.
    What is the matter? Did anybody have the same problem?

    Not I got next problem:
    when I cannot pass parameter to stored procedure and get array fro it. In other words returning array from procedure and passing some input parameters to it does not word!
    Does anybody know why it happens?

  • Add an array of strings into ArrayList

    Hi Guys
    I would like to add an array of strings into an ArrayList, which i have implemented by using the following code:-
    String[] strReturnWords = getInput2(line);
    List.add(strReturnWords);strReturnWords returns an array of Strings.
    How do i retrieve the array of strings from the ArrayList. I have tried
    String[i] strString = List.toString();Am i doing this correctly, are their any other ways??
    Many thanks
    Jason

    That should work.NO. That wont work AT ALL.
    This:
    String[] arrayOfString = new String[listName.size()];Is not right. The number of elements in the list is MUCH different
    then the size of the array which is an element in the list.
    This:
    arrayOfStrings[ i] = (String)listName.get(i);Will fail. The list contains an Object of StringArray not an Object of String.
    import java.util.*;
    public class StringList{
    public static void main(String[] args){
         String text = "this is some text";
         String[] words = text.split("\\s+");
         ArrayList list = new ArrayList();
         list.add(words);
         String[] array = (String[])list.get(0);
         for(int i = 0; i < array.length; i++){
         System.out.println("Word: " + array);

  • Start, Stop, Step array builder

    I would like to enter the start, stop, and step frequency to build an array that will hold the value's to feed to a sweep generator.
    I have something that works, except for one thing; the stop value. I can't seem to get this thing to stop on the stop frequency value. The step value seems to affect this too. So could anyone take a look at my vi, and help me with this? also, the code looks a little complex for what might seem like a simple thing to do.
    Solved!
    Go to Solution.
    Attachments:
    StartStopSTepFrequency.vi ‏10 KB

    Anyway, here's a slightly simpler implementation of your code. As you can see, you codes was way more complicated than needed!
    Shown below is the ramp pattern implementation (recommended). Both give the same result for sane inputs.
    I would definitely use the ramp pattern, because it has better error handling (e.g. if the delta is zero or max is +Inf, etc.).
    You can look at the code of it to learn something.
    You need to be a bit careful with possible accumulations of binary errors, especially with fractional steps that cannot be fully represented in binary (e.g. 0.1) 
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    RampByDelta.png ‏9 KB
    StartStopSTepFrequencyMOD.vi ‏12 KB

  • Word counting

    hello im looking to count the frequency of words in a document . can anyone suggest some suitable classes for doing this ive been looking at the hashtable but it seems a bit much for this task however im not sure what else is good
    all suggestions welcome
    thanx

    It's not a bit much, it's very space efficient and quick. Let the value you add to the Hashtable be an Int-class which you can set a new value, so you needn't replace existent value.
    Int count=table.get(...)
    if(count==null){
    count=new Int(0);
    table.put(...,count);
    count.inc();
    Gil

  • Compare int[] array

    Hi!
    Could you please help me how can I can compare two int[] array?
    I've got int[] a and int[] b
    I have tried a.equals(b) but even if all the elements are the same, it returns false.
    Should compare any elements in the array?
    Thanks for your help.

    See the javadoc for java.util.Arrays.equals()
    equals
    public static boolean equals(int[] a,
    int[] a2)
    Returns true if the two specified arrays of ints are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.
    Parameters:
    a - one array to be tested for equality.
    a2 - the other array to be tested for equality.
    Returns:
    true if the two arrays are equal.

  • How would I do this?

    I have to say I'm completely lost. I need to make two files - WordFrequencyAnalyzer.java that has all the functions and TestWordFrequencyAnalyzer.java that should be a GUI that calls the first one. I know how to make GUIs without a problem but its these functions that baffle me.
    This is what I need to do - WordFrequencyAnalyzer.java needs to have a constructor that opens us a text file and reads it and saves what is needed for analysis. This is what I have:
    public void WordFrequencyAnalyzer(String filename) throws IOException
         {//Constructor.  Uses file name to open file reads it, saving what is needed, then closes the file.
               BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename))));
         }Now these are killing me:
    public int frequency(String word)
    *****This needs to be able to check the number of times the particular word occurs in the file. How would I do this? Please help give me a clue. The next few seem to tie in together if I could figure out how to do one of them.
    public String mostFrequentWord()
    //The word that occurs most often in the file
    public String[] wordsOccurringAtLeast(int minimumNumberOfTimes)
    //An array, alphabetized, of all the words occurring at least the given minimum number of times...I'd figure I'd use a search and compare method here.
    public int numberOfWords()
    //The number of words (counted once each) in the file
    public String toString()
    //Returns a string which, when printed, will show two columns, with a word on each line on the left and its frequency on the right. The result must be alphabetized.
    Who could give me some pointers. I don't want the code done for me because I need to learn too. Do I need to put the data from the text file into a Collection interface in the java.util package or should I use something else?? And how would I go about doing something like that?
    Thank you very much,
    Henry

    I modified the code above for the Hashtable to a Collection and came up with this and emailed him:
         What about this:
         Collection words = new Collection();
         String line;
         while ((line = br.readLine()) != null)
         StringTokenizer st = new StringTokenizer(line);
         while (st.hasNext())
         { words.add(st.next().toString());
         Storing in a Collection is what you want right? I don't want to do something that you don't approve of. I remember the time I used a Hashtable and you didn't like it. ...
    This is his response:
    As for your suggested solution: A collection is a good idea, but Collection is
    an interface, so you can't do anything like
    Collection words = new Collection();
    You must figure out what kind of collection to use. And here's a hint about
    something else:
    If every time you see a word like "the" you store it in the collection, you'll
    have two problems: the word will be stored over and over, which is inefficient
    use of space, and your program will have to do a lot of repetitive work to
    implement the methods, which is inefficient use of time.
    I new he wanted a Collection. I'm starting to know him a little better now I guess, which still doesn't help as much. If anyone has any ideas please post - this is all new to me. Does anyone know the best kind of Collection to use as he put it?
    Thanks,
    Henry

  • String counting characters

    Hie every one! I need help. I have written a program that ask the user to enter string, at the mmont it counts number of words, number of vowel , number of consonts.
    Problem i am trying to solve is (1) when it counts characters i want to avoid counting numbers and things like ?;'".
    (2) how do word frequency and word occurrence
    this is what i have done and the rest is of the code i have left them
    //I want this program to throw exception if the user enters numbers
         String str;
         System.out.print("Enter a String: ");
         str = sc.nextLine();          
              for (int j=0; j<str.length();j++)
                             for (int i=0; i<vowles.length;i++)
                             ch = str.charAt(j);
                                  if(ch==vowles)
                                       total++;
                        if(str.charAt(j)== ' ')
                        word++;
         chcount = str.length() - word;
         System.out.println("Number of words =" + (word+1));
         System.out.println();
         System.out.println("number of vowels is =" + total);
         System.out.println("Number of characters =" + (str.length() - word));
         int cons = chcount - total;
         System.out.println("number of conconast =" + cons);

    Take a look at the Character and String classes. They have the methods you require.
    Look at these:
    Character.isLetter('A');
    Character.isDigit('A');Also if you want to check if a word is repeating then you could keep all your inputs in an array and you could check through each element (iterate) against the latest input using the equals mehtod.
    See here for more info.
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Character.html
    http://home.cogeco.ca/~ve3ll/jatutor7.htm
    http://www.devdaily.com/blog/Content/2/8/178/
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html
    Come back if you get stuck!

  • Problem with Indexer

    Hi,
    i am trying to develop a small search engine... currently i am trying to develop STOPLIST..... which iterates through piece of text and extracts different words and their respective frequencies... here is the piece of code which does this :
    ======================================
    for( int c=0; c < lines.size(); c++) {
    temp = lines.elementAt(c).toString();
    temp = temp.toLowerCase();
    st = new java.util.StringTokenizer(temp);
    while( st.hasMoreTokens())
    words.addElement(st.nextToken());
    for( int b=0; b < words.size(); b++) {
    extractedWord = words.elementAt(b).toString();
    for( int a=0; a < words.size(); a++) {
    if( words.elementAt(a).toString().equalsIgnoreCase(extractedWord))
    extractedWordFreq++;
    extractedWords.addElement(extractedWord);
    extractedWordsFreq.addElement(Integer.toString(extractedWordFreq));
    extractedWordFreq=0;
    for( int z=0; z < extractedWords.size(); z++)
    System.out.println("Extracted Terms : " + extractedWords.elementAt(z).toString() + " Freq : " + extractedWordsFreq.elementAt(z).toString());
    ========================================
    the only problem with above code is that .... it takes a long time to
    execute... around 30 seconds....
    Here is the spec of my pc :
    P4 : 512 MB RAM
    The piece of text has around 7500 words
    when i execute this code... and look at my Windows Task Manager....
    CPU usage goes to 100 %.....
    All I wanna know is that ... is there any way to change this code so that it executes more swiftly.....
    thanx in advance
    have fun

    Hi
    I read your previous reply: Vector, Array, StringTokenizer, etc. They are "heavy weight" not concerning to peformance so your code uses brute force.
    I found an example dealing with this issue and I believe to be faster than your but you must to modify details:
    import java.io.*;
    import java.util.TreeMap;
    import java.util.Iterator;
    public class WC {
      public static void main(String args[]) throws IOException {
        if (args.length != 1) {
          System.err.println("Usage: java WC <textfile>");
          System.exit(10);
        File file = new File(args[0]);
        StreamTokenizer stream = new StreamTokenizer(
                                       new FileReader(file));
        // treat any punctuation as word delimiters
        stream.whitespaceChars('!', '/');
        stream.whitespaceChars(':', '@');
        WordFrequencyCounter wfr = new WordFrequencyCounter();
        String word;
        int countNumbers = 0;
        while (stream.nextToken() != StreamTokenizer.TT_EOF)
          if (stream.ttype == StreamTokenizer.TT_WORD) {
            word = stream.sval;
            wfr.count(word);
          else if (stream.ttype == StreamTokenizer.TT_NUMBER) {
            countNumbers++;
        System.out.println("File: " + args[0] + " (" + file.length() + " bytes)"
                           + "\n#lines = " + stream.lineno()
                           + "\n\n#words = " + wfr.size()
                           + "\n#numbers = " + countNumbers + "\n");
        for (Iterator it = wfr.keySet().iterator(); it.hasNext();) {
          word = (String) it.next();
          System.out.println(wfr.frequency(word) + " " + word);
    class WordFrequencyCounter extends TreeMap {
      // first see if this word has already been encountered;
      // if not, then create a fresh counter for it;
      // otherwise, increment its counter
      public synchronized int count(String word) {
        Integer counter = (Integer) get(word);
        counter = (counter == null) ? new Integer(1)
                      : new Integer(counter.intValue() + 1);
        put(word, counter);
        return counter.intValue();
      // find out how many times this word has been encountered
      public synchronized int frequency(String word) {
        Integer counter = (Integer) get(word);
        return (counter == null) ? 0 : counter.intValue();
    }Regards.

  • Please help with Boggle game

    The Input
    The input file is exactly as in WordSearch.java and in fact, you can reuse almost the entire program, especially the routines to read the word and puzzle files. In order to limit the amount of output words that are less than nine characters are not to be considered matches.
    Strategy
    First, provide a Position class to store a row and column as a pair, and provide a constructor, toString, and equals (hashCode would also be good to have, but is not needed). Make sure Position is an immutable type.
    Next, change solvePuzzle to solveBoggle as follows:
         * Routine to solve the Boggle game.
         * @return a Map containing the strings as keys, and the positions used
         *     to form the string (as a List) as values
        public Map solveBoggle( )
            Map results = new HashMap( );
            List path = new ArrayList( );
            for( int r = 0; r < rows; r++ )
                for( int c = 0; c < columns; c++ )
                    solve( new Position( r, c ), "", paths, results );
            return results;
        }Observe that solveBoggle calls the routine solve for each position in the grid. solve is recursive, and implementing it is virtually the entire assignment. After you implement solve you should have a routine that can print out, in a nice form, the Map returned by solveBoggle.
    The specification for the recursive solve routine is:
         * Hidden recursive routine.
         * @param thisPos the current position
         * @param charSequence the characters in the potential matching string thusfar
         * @param path the List of positions used to form the potential matching string thusfar
         * @param results the Map that contains the strings that have been found as keys
         *       and the positions used to form the string (as a List) as values.
        private void solve( Position thisPos, String charSequence, List path, Map results )
            /* Less than one page of code will do it. */
        }In implementing solve you will want to do the following:
    Attach the character at thisPos to charSequence.
    If the resulting current string is not a prefix of any word in the dictionary, you can return.
    Otherwise, you will want to update the path variable, and look for some matches.
    If the current string is a word in the dictionary you want to update the map.
    In any event, you want to recursively call solve with appropriate parameters, on all adjacent positions, skipping those that have already been used in the current string, and being careful not to wander off the end of the board.
    Don't forget to update the path variable when you return from solve.
    Copying and Cloning
    As much as possible, you should avoid making copies of variables. In particular, the last two parameters to solve (the List and Map are to be the same object for each unique invocation of solveBoggole. YOU MAY NOT MOVE THEM TO BE CLASS VARIABLES. However, what this means is that when you put a String as a key and a List as a value into the Map, you will need at that point to make a copy of the List, since otherwise the Map would simply be storing lots of references to the same single list (which would be empty at the end of the program). You can use any of the List (subclasses) constructors to create a List from another List.
    This is the puzzle file:
    fozepdkdnqlhfejdzksccfykdxnlorwvfwavbmyqclxjrgntqhvuowgrtufhnbdt
    zfqatqryeqhxxuqpdmmsksjdooncssvrznssflsjbahawxsalesvwdblsqpkimdj
    zxdeiwqmwxouwgukkmfjqiwkynwizztyxxehtuvrtklqsgaduhomsmyszwbywwyv
    teeozafumtmebojvwxkqliimhlmfikabpgsqizkuszztnirlibbtlkgsvuzdfbhw
    iboqaaltzkmnsdycgawukeohyonfpwdxxrqxubqtnfghkhkrhintobcorpwhlzgi
    tyinbyiofryqykjhswcizgwrwsajuiuphceicmzifxyfjhodfqlexhxvcxgyganp
    erxhfyrnxpsgyhjdzuhyefviecgkcvbhozqvzhixyddwkpzllikrpfzuhhgmeivu
    jlqiuafsdlopapbnxlfnsehaopmsxjpgufpofwglhwajlbxkmcxfighwwvrtegca
    nroupwfxugifhfpwjpdsxmqthjpnrrngkdbzbgyvojcwqtuakzuilmbuyshplwwv
    bzxcfxzugdszwozhnvryhushnbxyxvwyuvcbsbxbgpccfblsyeshzmpmnommjimf
    fogarebxvdcbgpvguonvachqsvebgrglhplbvoaqtetzuphqdvlfzuxsrcvxvele
    twfolgggmaigppyumlbmhzgzdbwyfhcagiqtqxzcxhlmxlilxjxeiddlhclolopr
    yfmqemubvhputxgsjdwtjchsgsirixlifxyljvnhccbxchplnogysnsygapqaazh
    azsluhszmwwofobuchuuxmsdpjtpmuyouqzoaupmqmavcdqemkajzuoqfkftefhy
    xhpxbejrslouogadtcmsydienpxrwfstojrppaiioyecfhhylwskzcomtnfpuzii
    izzycjiqiounxcnjaftzjjncyurtuzdebfedomvybrnavajvhewqnjsogljclmgo
    tltizoicfwdbwmygrvwggrumcdopsxdliwvjmemuapxydvewsddzwznyfcozztmj
    siseogaqvxozvvxnaamwcawjemkfgwqaekesrfioeznzwnnwpburdqchdmoljelp
    priiyswdtmepztnovhiaakkfzyqifdxwuhetcayvmcnlwcctkkvmufrtejdlmdhi
    klbonbmagzncbpxnbszwasrgbxrpayymlbbydnyjoonpfmfhgedgzwmatdsvdqio
    rjnuwnfkdsbjegqlnvrmrgonlgiryqfqbumzkslnknwrvmckjvwddnqpvagutnkw
    kwwuqhjbwguuuyegtdjzsbqnbyhwnttxsrtiadlxlfthdxnzcwauxqiborzbnubf
    lupmzblkieumdhnigncdfmgtgiwtcxaoupctqngbtanyhcinrntwzbphjnconceh
    ugckvinqiaqsezhvmcrneivpyxdlcjswpuimfwcpythfuragtutzeqrcqupsgjqv
    gyilwmavhkabbchuwdudtlhlhxdngtlmuvxqhanrkpslscfqfbtaodmyarlinyvh
    tuzdupugeorwqzpvakyrnkpnbcwobtxwnzbkoxqsmkrcjgalqyceittlwrczkzxa
    yzmmwehioynzenlwlpatjwghnigaidcieoxdueljeakknvgyljtwhaduklwuqydv
    ocylglummewbceapnvnuxqridpctqhoejorrcldqsbrwgtnvraqoqjytydookdvw
    tmnxatnuuhsacfwtfokvzkqxpeoajlyfxlczgstbbnddszzxpluoxkmnrcpcnnhm
    ammhehifvlknnjlcwfrusfhljwnwjxiljwspeaubogobqbfojyiddpqondkycvkn
    recxfyyvfpyxqdlbcwehnuwbaibcdlqxquuxttuyisxyxicbggludjvfrwjxkbuc
    wobrhvprposmyuqfcbzhkumdswaezwivljmugdmxrekqycxadwipswsmsvrsrzpc
    lexrhlpbpbtpfqpimzxgwrsqmjkelciyghrpsiqhjlwqboyppxxnrqgdbsjousmc
    besumkdywaozqprfmovfgbjituwqolsqpmkbxnzvpquffnnteizklkueetutepjv
    bvwykytaqqhvfwojgnurxqyejuxpjiklfjlpjhrzzbuexkqeamvzctdoocdzmqmr
    bajkjajibfozpefrqcrvywjobonngafhcorlqcvshjtzqaqicjdagmohdewjgbti
    rkvknqewbxvrzoabxdefsuoxalggmzqgmlsbbwxfvvwulyxicbqwyetypbhedxmp
    jeqmaprvmqrxooissyoqchqslxyovkdgovuomolzecyssglmgbejjvduubiplnxb
    kspwicxmgyeyernltrwembahckypxyqhshfalfmrdsrhmeuhwslkvltzxuouugdm
    pkoapcrsulcipypntcaoptompcijlnxaylbnnuikfksxkkmdmmseigqzkbjvogym
    sbchvkrdwkcgwokkdconkhmuixswgqlarphobztxlvdjmptptiedrsazquxykkyd
    zhtainzvkfewuynqirvzkvacpzcbkagljcmsrnpbsuypulfefafpyhtpgvtqxbcg
    dqaudswyownkjsoouvfscykkvdbsefbkxdgcveajantkhjacegwiggtclwusdxcc
    bkeyphirwddepegvkeeslzuyxrqcouerfkquranofruuvaqhgwzrxuquniwbdcti
    mjeglrwqiqlfsdoyzoswkksxsoyvqtfeejkpdiinyvtsyhtxxlvhvngpdhlvaqbh
    coyhwguxbppbzkawvvgskmipvtmylofpcfwymtxpiprhzrgvpopbaxrysdwgrdvv
    iuwwntmviffiwlfnzwpbugbolxwfaualoyhdsvycafmzsrmtqbxkjyavyxcarclh
    btkvokxrskqkdcgtgdfpbimbfocytnhwitrzdqqvagigkobqthiwrwywlawgnfcy
    yvxdlnbmvjufzvyseiovemtrorxewbcwwzaiobwjmsolnoduwtpdglwucuybxcxu
    bzepaaamspxhfcdewthegdaizblxdlthkzwlbxzvoxcvbgzxbgdhmerlhfkkqfra
    eqnfpnadmfynlynogqxswqgdvsqlyhocxbkmokrapsqcsdsyvptugzzdtpprxfww
    gglxsezkwpoouhpqyikgjjkebbwyguwoajluolekcvbxeqpcabllmxpnynnghkuj
    tgejtkwvfxujpjmrkzexwtkujycqkwafcgpxqlvwkpfzztsjswgqrtmatotdltkp
    bznrminyxvxyopijnqzfjmfcayhntsdutsoicdgzygapxiylazqknxooyybrsgol
    yevahecgkcvjmvumwmykkpyinbbfkrsivqlfupletinffktbwslijlswpwdzpxjn
    nwshlfnepdlupfxlzjwiwognkloaianywhhkmvobaaxphucgfyqcnwrzhgbrgqpe
    xxolufmuhjjoelwlmmnbiharneivwyzuvqfrvulcfwsjjovvakwktzbidjdbjfvg
    vdxszkwegoqqenlexkqtjrbocfpmmnujssbrezvlnlbryoxyanrjguzibrwnetyy
    nbprakcpyfgywfwwupiakjllajbgczerbtjbgnrgtzerhdnbuxeehrshatqfuuwv
    qhzwvqeorihanueiuimbzgkbbagwxfrnmqjhinxcxeclbgtvqhyrqitrlbnigfvv
    xgeivcmuiohlxagpkgharcrcdhmmojhlrlvophiyyqjvssmeatervyvbfhntswgj
    jcxzlizjykgsetxfmbykbulibyduwkffodgzlhjlupdakahxeghfasqdstzodfvt
    kctxleifvnggonfutobvgrzalyoqfjkrnfozlyegmmocctwvhztprspesfuargrg
    lgfwemfsatucpsywurollfrflnfeuxkhfsgleleegahvvhupakanptsagaeaxrke
    the dictionary file is too big to post but it is something like this:
    a
    aah
    aardvark
    aardvarks
    aardwolf
    aardwolves
    aba
    abaca
    abaci
    aback
    abacterial
    abacus
    abacuses
    abaft
    abalone
    abalones
    abandon
    abandoned
    abandoning
    abandonment
    abandons
    abase
    abased
    abasement
    abasements
    abases
    abash
    abashed
    abashes
    abashing
    abashment
    abashments
    abasing
    abatable
    abate
    abated
    abatement
    abater
    abaters
    abates
    abating
    abatis
    abatises
    abattoir
    abattoirs
    abaxial
    abbacies
    abbacy
    abbe
    abbess
    abbey
    abbot
    abbots
    abbreviate
    abbreviated
    abbreviates
    abbreviating
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    // WordSearch class interface: solve word search puzzle
    // CONSTRUCTION: with no initializer
    // ******************PUBLIC OPERATIONS******************
    // int solvePuzzle( )   --> Print all words found in the
    //                          puzzle; return number of matches
    public class WordSearch
         * Constructor for WordSearch class.
         * Prompts for and reads puzzle and dictionary files.
        public WordSearch( ) throws IOException
            puzzleStream = openFile( "Enter puzzle file" );
            wordStream   = openFile( "Enter dictionary name" );
            System.out.println( "Reading files..." );
            readPuzzle( );
            readWords( );
         * Routine to solve the word search puzzle.
         * Performs checks in all eight directions.
         * @return number of matches
        public int solvePuzzle( )
            int matches = 0;
            for( int r = 0; r < rows; r++ )
                for( int c = 0; c < columns; c++ )
                    for( int rd = -1; rd <= 1; rd++ )
                        for( int cd = -1; cd <= 1; cd++ )
                            if( rd != 0 || cd != 0 )
                                matches += solveDirection( r, c, rd, cd );
            return matches;
         * Search the grid from a starting point and direction.
         * @return number of matches
        private int solveDirection( int baseRow, int baseCol, int rowDelta, int colDelta )
            String charSequence = "";
            int numMatches = 0;
            int searchResult;
            charSequence += theBoard[ baseRow ][ baseCol ];
            for( int i = baseRow + rowDelta, j = baseCol + colDelta;
                     i >= 0 && j >= 0 && i < rows && j < columns;
                     i += rowDelta, j += colDelta )
                charSequence += theBoard[ i ][ j ];
                searchResult = prefixSearch( theWords, charSequence );
                if( searchResult == theWords.length )
                    break;
                if( !((String)theWords[ searchResult ]).startsWith( charSequence ) )
                    break;
                if( theWords[ searchResult ].equals( charSequence ) )
                    numMatches++;
                    System.out.println( "Found " + charSequence + " at " +
                                        baseRow + " " + baseCol + " to " +
                                        i + " " + j );
            return numMatches;
         * Performs the binary search for word search.
         * @param a the sorted array of strings.
         * @param x the string to search for.
         * @return last position examined;
         *     this position either matches x, or x is
         *     a prefix of the mismatch, or there is no
         *     word for which x is a prefix.
        private static int prefixSearch( Object [ ] a, String x )
            int idx = Arrays.binarySearch( a, x );
            if( idx < 0 )
                return -idx - 1;
            else
                return idx;
         * Print a prompt and open a file.
         * Retry until open is successful.
         * Program exits if end of file is hit.
        private BufferedReader openFile( String message )
            String fileName = "";
            FileReader theFile;
            BufferedReader fileIn = null;
            do
                System.out.println( message + ": " );
                try
                    fileName = in.readLine( );
                    if( fileName == null )
                         System.exit( 0 );
                    theFile = new FileReader( fileName );
                    fileIn  = new BufferedReader( theFile );
                catch( IOException e )
                  { System.err.println( "Cannot open " + fileName ); }
            } while( fileIn == null );
            System.out.println( "Opened " + fileName );
            return fileIn;
         * Routine to read the grid.
         * Checks to ensure that the grid is rectangular.
         * Checks to make sure that capacity is not exceeded is omitted.
        private void readPuzzle( ) throws IOException
            String oneLine;
            List puzzleLines = new ArrayList( );
            if( ( oneLine = puzzleStream.readLine( ) ) == null )
                throw new IOException( "No lines in puzzle file" );
            columns = oneLine.length( );
            puzzleLines.add( oneLine );
            while( ( oneLine = puzzleStream.readLine( ) ) != null )
                if( oneLine.length( ) != columns )
                    System.err.println( "Puzzle is not rectangular; skipping row" );
                else
                    puzzleLines.add( oneLine );
            rows = puzzleLines.size( );
            theBoard = new char[ rows ][ columns ];
            Iterator itr = puzzleLines.iterator( );
            for( int r = 0; r < rows; r++ )
                String theLine = (String) itr.next( );
                theBoard[ r ] = theLine.toCharArray( );
         * Routine to read the dictionary.
         * Error message is printed if dictionary is not sorted.
        private void readWords( ) throws IOException
            List words = new ArrayList( );
            String lastWord = null;
            String thisWord;
            while( ( thisWord = wordStream.readLine( ) ) != null )
                if( lastWord != null && thisWord.compareTo( lastWord ) < 0 )
                    System.err.println( "Dictionary is not sorted... skipping" );
                    continue;
                words.add( thisWord );
                lastWord = thisWord;
            theWords = words.toArray( );
          // Cheap main
        public static void main( String [ ] args )
            WordSearch p = null;
            try
                p = new WordSearch( );
            catch( IOException e )
                System.out.println( "IO Error: " );
                e.printStackTrace( );
                return;
            System.out.println( "Solving..." );
            p.solvePuzzle( );
        private int rows;
        private int columns;
        private char [ ][ ] theBoard;
        private Object [ ] theWords;
        private BufferedReader puzzleStream;
        private BufferedReader wordStream;
        private BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
    }Thank you in advance

    Ok, I'm stuck. Please somebody. It seems like I'm not moving inside the board. This is what I have done so far:
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.HashMap;
    public class WordSearch
         * Constructor for WordSearch class.
         * Prompts for and reads puzzle and dictionary files.
        public WordSearch( ) throws IOException
            puzzleStream = openFile( "Enter puzzle file" );
            wordStream   = openFile( "Enter dictionary name" );
            System.out.println( "Reading files..." );
            readPuzzle( );
            readWords( );
           * Private class Position is a class to store a row and a column
           * as a pair.
        private class Position
             int row;
             int column;
                * A constructor from two integers
                * @param r is the row of the position
                * @param c is the column of the position
             Position( int r, int c )
                  row = r;
                  column = c;
                * First accessor
                * @return the row as an int
              public int getRow( )
                   return row;
                * Second accessor
                * @return the column as an int
              public int getColumn( )
                   return column;
                * Position objects are equal if both rows and columns are equal
                 * @return true if both rows and columns are equal; false otherwise
              public boolean equals( Object aPosition )
                   int x = ( (Position) aPosition ).getRow( );
                   int y = ( (Position) aPosition ).getColumn( ); 
                 return ( ( row == x ) && ( column == y ) );
                * Returns a String representation of Position
                   * @return a String with Position as ( x, x )
              public String toString( )
                 return ( "( " + row + ", " + column + " )" );
        } // end of Position
         * Routine to solve the Boggle game.
         * @return a Map containing the strings as keys, and the positions
         * used to form the string (as a List) as values
        public Map solveBoggle( )
            Map results = new HashMap( );
            List path = new ArrayList( );
            boolean[][] marked = new boolean[rows][columns];
            for( int r = 0; r < rows; r++ )
                 for( int c = 0; c < columns; c++ )
                    solve( new Position( r, c ), "", path, results, marked);
            return results;
         * Hidden recursive routine.
         * @param thisPos the current position
         * @param charSequence the characters in the potential matching string thusfar
         * @param path the List of positions used to form the potential matching string thusfar
         * @param results the Map that contains the strings that have been found as keys
         * and the positions used to form the string (as a List) as values.
        private void solve( Position thisPos, String charSequence, List path, Map results,
                  boolean[ ][ ] marked )
             int row = thisPos.getRow( );
             int col = thisPos.getColumn( );
             charSequence += theBoard[ row ][ col ];
            int searchResult = prefixSearch( theWords, charSequence );
            if( searchResult == theWords.length )
                   return;
              if( theWords[ searchResult ].equals( charSequence ) )
                 path.add( thisPos );
                 results.put( charSequence, path );
                 path.clear( );
                 charSequence.replaceAll( charSequence, "" );
                 return;
            if( !( (String)theWords[ searchResult ] ).startsWith( charSequence ) )
                 return;
            else
                 path.add( thisPos );
                 marked[ thisPos.getRow( ) ][ thisPos.getColumn( ) ] = true;     
                   if( ((row-1) >= 0) && ((col-1) >= 0) && !marked[row-1][col-1] )
                        marked[row-1][col-1] = true;
                        solve( new Position(row-1, col-1), charSequence, path, results, marked);
                   if( ((row-1) >= 0) && !marked[row-1][col] )
                        marked[row-1][col] = true;
                        solve( new Position(row-1, col), charSequence, path, results, marked);
                   if( ((row-1) >= 0) && ((col+1) < columns) && !marked[row-1][col+1]  )
                        marked[row-1][col+1] = true;
                        solve( new Position(row-1, col+1), charSequence, path, results, marked);
                   if( ((col-1) >= 0) && !marked[row][col-1]  )
                        marked[row][col-1] = true;
                        solve( new Position(row, col-1), charSequence, path, results, marked);
                   if( ((col+1) < columns) && !marked[row][col+1] )
                        marked[row][col+1] = true;
                        solve( new Position(row, col+1), charSequence, path, results, marked);
                   if( ((row+1) < rows) && ((col-1) >= 0) && !marked[row+1][col-1] )
                        marked[row+1][col-1] = true;
                        solve( new Position(row+1, col-1), charSequence, path, results, marked);
                   if( ((row+1) < rows) && !marked[row+1][col] )
                        marked[row+1][col] = true;
                        solve( new Position(row+1, col), charSequence, path, results, marked);
                   if( ((row+1) < rows) && ((col+1) < columns) && !marked[row+1][col+1] )
                        marked[row+1][col+1] = true;
                        solve( new Position(row+1, col+1), charSequence, path, results, marked);
         * Performs the binary search for word search.
         * @param a the sorted array of strings.
         * @param x the string to search for.
         * @return last position examined;
         *     this position either matches x, or x is
         *     a prefix of the mismatch, or there is no
         *     word for which x is a prefix.
        private static int prefixSearch( Object [ ] a, String x )
            int idx = Arrays.binarySearch( a, x );
            if( idx < 0 )
                return -idx - 1;
            else
                return idx;
         * Print a prompt and open a file.
         * Retry until open is successful.
         * Program exits if end of file is hit.
        private BufferedReader openFile( String message )
            String fileName = "";
            FileReader theFile;
            BufferedReader fileIn = null;
            do
                System.out.println( message + ": " );
                try
                    fileName = in.readLine( );
                    if( fileName == null )
                         System.exit( 0 );
                    theFile = new FileReader( fileName );
                    fileIn  = new BufferedReader( theFile );
                catch( IOException e )
                  { System.err.println( "Cannot open " + fileName ); }
            } while( fileIn == null );
            System.out.println( "Opened " + fileName );
            return fileIn;
         * Routine to read the grid.
         * Checks to ensure that the grid is rectangular.
         * Checks to make sure that capacity is not exceeded is omitted.
        private void readPuzzle( ) throws IOException
            String oneLine;
            List puzzleLines = new ArrayList( );
            if( ( oneLine = puzzleStream.readLine( ) ) == null )
                throw new IOException( "No lines in puzzle file" );
            columns = oneLine.length( );
            puzzleLines.add( oneLine );
            while( ( oneLine = puzzleStream.readLine( ) ) != null )
                if( oneLine.length( ) != columns )
                    System.err.println( "Puzzle is not rectangular; skipping row" );
                else
                    puzzleLines.add( oneLine );
            rows = puzzleLines.size( );
            theBoard = new char[ rows ][ columns ];
            Iterator itr = puzzleLines.iterator( );
            for( int r = 0; r < rows; r++ )
                String theLine = (String) itr.next( );
                theBoard[ r ] = theLine.toCharArray( );
         * Routine to read the dictionary.
         * Error message is printed if dictionary is not sorted.
        private void readWords( ) throws IOException
            List words = new ArrayList( );
            String thisWord;
            while( ( thisWord = wordStream.readLine( ) ) != null )
                words.add( thisWord );          
            theWords = words.toArray( );
            Arrays.sort( theWords );
           * Prints a String representation of the words found and their List of positions.  
           * @Prints a String with the words found and their List of positions.
        public static void printMap( Map wordMap )
             Iterator itr1 = wordMap.entrySet( ).iterator( );
             String str = "";        
            while( itr1.hasNext( ) )
                 String aWord = (String)( (Map.Entry)itr1.next( ) ).getKey( );  
                 str += "Found " + aWord + " at ";
                 Iterator itr2 = ( (List)( ( (Map.Entry)itr1.next( ) ).
                           getValue( ) ) ).iterator( );
                 while( itr2.hasNext( ) )
                      str += (Position)itr2.next( );
                      if( itr2.hasNext( ) )
                           str += ", ";
                      else
                           str += "\n";
             System.out.println( str );
         } // end of printMap
          // Cheap main
        public static void main( String [ ] args )
            WordSearch p = null;
            try
                p = new WordSearch( );
            catch( IOException e )
                System.out.println( "IO Error: " );
                e.printStackTrace( );
                return;
            System.out.println( "Solving..." );
            Map wordMap = p.solveBoggle( );
            p.printMap( wordMap );
        private int rows;
        private int columns;
        private char [ ][ ] theBoard;
        private Object [ ] theWords;
        private BufferedReader puzzleStream;
        private BufferedReader wordStream;
        private BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
    }Thanks

Maybe you are looking for

  • ITunes error -50 - iPod cannot be updated

    Hi, I've updated iTunes to the most recent version (5.0.0.35) on Windows XP. When I try to update my iPod (4th Gen Click Wheel, most recent iPod update (september's) run) everything is fine. When I try to update with Outlook's contacts, that's fine a

  • IPod Nano Black 1gb error installing ipod drivers

    Hi there i just bought an IPOD Nano Black. My problem is that i want to install the drivers for the ipod but i'm getting an error: 1608: Unable to create InstallDriver instance, Return code: -2147024894 I don't know what to do can anyone help me with

  • Exception occurred during internal http communication

    Hello Everyone, We are getting the following error when we call the bsp application ( http://hostname.domain.com:8000/sap(bD1lbiZjPTgwMCZkPW1pbg==)/bc/bsp/sap/crm_ui_start/default.htm) An error occurred during initialization of the application An exc

  • How can I get Pandora to load on my Ipod Touch

    How can I get Pandora to load on my IPod Touch?

  • One-time ship to Party on Item Level

    Dear SD Experts, Can you throw some light on the scenario below? Scenario: Customer order 2 pcs of MATERIAL A, 1 pc of MATERIAL B to be delivered to 2 different ship to parties. Sold to: 1000 Material A           1pc        One-time Ship-to-Party 200