我想在java中的二维数组上实现顺序搜索。Java搜索2D字符串数组
我目前有两个类。在第一类中,用户将数据值输入到数组中,并输入他希望搜索的项(在他刚输入的数组/数据值中)。
该搜索由一个方法(第二类)处理,该方法执行顺序搜索,然后将结果传递回第一类。
我一直在使用这下面的代码试过,但顺序查找工作不...
文件#1(输入文件):
static public void s_2d_string() {
int counter,x;
counter = 2;
String[][] sortValues = new String[counter+1][2];
for (x=0;x<counter;x++) {
System.out.print("Enter book name: ");
sortValues[x][0] = readLine();
System.out.print("Enter book author: ");
sortValues[x][1] = readLine();
}
System.out.print("Which column would you like to sort by? 1 or 2? ");
String sortBystring = readline();
int sortBy;
sortBy = Integer.parseint(sortBystring);
sortBy = sortBy-1;
System.out.print("Enter search term: ");
String searchterm = readLine();
sortValues = s.sort(sortValues,counter, sortBy, searchterm);
int flagcounter_int = Integer.parseInt(sortValues[0][0]);
System.out.println(flagcounter_int + " results found.");
for (x=0;x<flagcounter_int;x++) {
System.out.println(sortValues[x+1][0] + ", " + sortValues[x+1][1]);
}
}
文件#2:
static public String[][] sort (String data[][], int totalNo, int sortBy, String searchterm) {
boolean found = false;
int flagcounter = 0;
if (sortBy == 0) {
for (int x=0; x<totalNo;x++) {
if (searchterm.equals(data[x][0])) {
found = true;
flagcounter = flagcounter+1;
data[flagcounter] = data[x];
}
}
}
if (sortBy == 1) {
for (int x=0; x<data.length;x++) {
if (searchterm.compareTo(data[x][1]) == 0) {
found = true;
flagcounter = flagcounter+1;
data[flagcounter] = data[x];
}
}
}
String flagcounter_string = Integer.toString(flagcounter);
data[0][0] = flagcounter_string;
return data;
}
具体问题是,如果我尝试在列“n”中搜索术语“k”,并且该术语“k”出现在第一行(无论哪一列),搜索函数将列出数组中结果找到的行数,并列出结果:行数,k(重复数组中的行数) 。如果“k”没有出现在第一行(搜索功能完美),则不会出现此问题。
如何解决这个问题?
我刚刚添加了“家庭作业”标签。没有绕过它。 – Bohemian 2012-07-10 18:53:42
什么不起作用?你做了什么来弄清楚什么是错的? – Marvo 2012-07-10 18:58:27
具体问题是,如果我尝试在列“n”中搜索术语“k”,并且术语“k”出现在第一行(不管哪列),搜索功能将列出*中的行数array *结果找到并列出结果:*行数*,k(重复数组中的行数)。如果“k”没有出现在第一行(搜索功能完美工作),则不会出现此问题... – 01jayss 2012-07-10 19:03:19