這是一個家庭作業問題。我有一個Java程序來計算某個模式/字符串是否在用戶輸入的文本字符串中。該程序工作,但總是輸出一個-1,這是它應該輸出的模式字符串不在指定的文本中。我無法弄清楚什麼是不工作的我的生活,我會對我需要解決的問題提供一點啓示。Horspool輸出錯誤
這裏是我的代碼:
import java.util.Scanner;
/**
* @author Mouse
*
*/
public class horspool {
/**
* @param args
*/
public static void main(String[] args)
{
Scanner scanIn = new Scanner (System.in);
//The text to search for the phrase in
String t = "";
//The phrase/pattern to search for
String p = "";
System.out.println(" ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Harspool's Algorithm: ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" ");
System.out.println("Please enter the full text: ");
t = scanIn.nextLine();
System.out.println("Please enter the pattern to search for: ");
p = scanIn.nextLine();
char[] text = new char[t.length()];
char[] pattern = new char[p.length()];
for (int i = 0; i < text.length; i++)
{
text[i] = t.charAt(i);
}
for (int i = 0; i < pattern.length; i++)
{
pattern[i] = p.charAt(i);
}
int newChar[] = new int[256];
for(int i=0; i < 256; i++)
{
newChar[i]=0;
}
for (int i = 0; i < text.length; i++)
{
newChar[t.charAt(i) % 256]++;
}
for (int i = 0; i < pattern.length; i++)
{
newChar[p.charAt(i) % 256]++;
}
int index = HorspoolMatching(pattern, text);
System.out.println("Index: " + index);
}
public static int[] ShiftTable(char[] p)
{
int m = p.length;
//Table filled with shift sizes for each individual letter.
int[] table = new int[256];
for (int i = 0; i < table.length; i++)
{
table[i] = m;
}
for (int j = 0; j < m - 1; j++)
{
for (int a = 0; a < p.length; a++)
{
if (p[j] == p[a])
{
table[a] = (m - 1 - j);
}
}
}
return table;
}
public static int HorspoolMatching(char[] p, char[] t)
{
int [] table = ShiftTable(p);
int m = p.length;
int i = m - 1;
int n = t.length;
int temp = 0;
int k = 0;
int count = 0;
while (i <= n - 1)
{
k = 0;
while (t[i - k] == p[m - 1 - k] && k < m - 1)
{
System.out.println("In second while");
k++;
}
if (k == m)
{
return (i - m + 1);
}
else
{
for (int a = 0; a < t.length; a++)
{
if (t[i] == t[a])
{
temp = table[a];
}
}
i = i + temp;
}
}
return -1;
}
}
任何幫助將不勝感激!非常感謝!
使用調試器,並通過一個小例子。此外,「程序起作用」,但「不起作用」並不合理。 – 2013-03-25 18:30:51