您的搜索方法正常运行。我创建了一个类并使用了你的搜索方法(COPIED AND PASTED,我甚至没有改变你的搜索)并且它可以工作。这使我相信问题在于你如何输入数据。
class Pdeuchler {
static Pdeuchler db;
String[][] bookdb;
public static String search(String term) {
String result = "";
int row = db.bookdb.length;
outer_loop: // CHANGE #1 added a named loop
for (int i=0; i<db.bookdb.length; i++) {
for (int j=0; j<4; j++) {
if (term.equals(db.bookdb[i][j])) {
row = i;
//break; //REMOVED
break outer_loop; // CHANGE #2 breaking to the outer_loop
}
}
}
if (row == db.bookdb.length) {
result += "Your search failed to return any results";
}
else {
for (int j=0; j<4; j++) {
result += db.bookdb[row][j] + " ";
}
}
return result;
}
public static void main(String[] args) {
db = new Pdeuchler();
db.bookdb = new String[10][4]; // title, author, publisher, year
db.bookdb[0] = new String[] {"Awesome Book","Stan","West","2001"};
db.bookdb[1] = new String[] {"Cool Story","Dan","North","2002"};
db.bookdb[2] = new String[] {"Brothers","North","North","2003"};
db.bookdb[3] = new String[] {"Never again!","Bob","West","2004"};
db.bookdb[4] = new String[] {"Howdy Partner","Stan","South","2005"};
db.bookdb[5] = new String[] {"What the StackOverflow?","Dan","North","2006"};
db.bookdb[6] = new String[] {"That's hilarious","Angie","South","2007"};
db.bookdb[7] = new String[] {"I like pie","Angie","East","2008"};
db.bookdb[8] = new String[] {"Bob writes a book","Bob","South","2009"};
db.bookdb[9] = new String[] {"The adverntures of Bob","Bob","North","2010"};
System.out.println(search("I like pie"));
System.out.println(search("North"));
System.out.println(search("Dan"));
}
}
而且结果:
C:\junk>java Pdeuchler
I like pie Angie East 2008
The adverntures of Bob Bob North 2010
What the StackOverflow? Dan North 2006
C:\junk>
,并与变化的结果:
C:\junk>javac Pdeuchler.java
C:\junk>java Pdeuchler
I like pie Angie East 2008
Cool Story Dan North 2002
Cool Story Dan North 2002
C:\junk>
如果我们采用了先进的搜索方法(我打电话搜索2),我们得到这个:
C:\junk>java Pdeuchler
simple search:
I like pie Angie East 2008
Cool Story Dan North 2002
Cool Story Dan North 2002
advanced search:
I like pie Angie East 2008
Cool Story Dan North 2002
Brothers North North 2003
What the StackOverflow? Dan North 2006
The adverntures of Bob Bob North 2010
Cool Story Dan North 2002
What the StackOverflow? Dan North 2006
C:\junk>
这里的先进海rch方法:
public static String search2(String term) {
String result = "";
int row = db.bookdb.length;
for (int i=0; i<db.bookdb.length; i++) {
for (int j=0; j<4; j++) {
if (term.equals(db.bookdb[i][j])) {
row = i;
for (int k=0; k<4; k++) {
result += db.bookdb[i][k] + " ";
}
result += "\n";
break; // breaks out of the INNER (j) loop
}
}
}
if (row == db.bookdb.length) {
result += "Your search failed to return any results";
}
return result;
}
您的搜索没有被打破。我测试了它(见下文)。我的猜测是,你的'bookdb'输入被破坏,总是把数据放在第一列。 – corsiKa 2011-03-29 18:17:38