This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Knuth Morris Pratt Search Algorithm Help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Knuth Morris Pratt Search Algorithm Help" Watch "Knuth Morris Pratt Search Algorithm Help" New topic
Author

Knuth Morris Pratt Search Algorithm Help

Niall Watchorn
Greenhorn

Joined: Mar 01, 2011
Posts: 2

Ok, I am trying to implement a KMP Search algorithm, but I'm getting an out of bounds exception, at like 59 ( if(W[i] == S[m + i]){ )

Any ideas?

Please help

My Algorithms class:



Main method:









I found the psuedo code for the KMP Algorithm and the failure function here:
KMP Psuedo Code

fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10928
    
  12

System.out.println() is your best friend.

right before your line 59, do something like

System.out.println("i is " + i ", and m is " + m + ".");

I'd also put in somewhere a "length of S is " + S.length();

then you can see what the values are just before it throws your OOB error.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Remember that variable names should be with lowercase letters. Also I would rename the variables into something with more meaning that i, n and m.


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
 
 
subject: Knuth Morris Pratt Search Algorithm Help
 
Similar Threads
Class Pattern - regular expressions
hash map error
generatinf pattern strings
RMI server client
AND operation in java RegEX and Pattern