It's not a secret anymore!
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 OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Knuth Morris Pratt Search Algorithm Help" Watch "Knuth Morris Pratt Search Algorithm Help" New topic

Knuth Morris Pratt Search Algorithm Help

Niall Watchorn

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

Joined: Oct 02, 2003
Posts: 11882

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.
I agree. Here's the link:
subject: Knuth Morris Pratt Search Algorithm Help
jQuery in Action, 3rd edition