要求从控制台输入需录入的书数目,然后依次输入书名。最后输入搜索关键字,从录入的书中检索匹配该关键字的书,并打印书名和索书号。优先按照匹配程度的顺序打印,其次按照字母顺序。实现代码如下:
import java.util.Arrays;
import java.util.Scanner;
public class SearchBook {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[] books = new String[n];
int[] fitValue = new int[1];
int[] bookNo = new int[1];
in.nextLine();
for(int i=0; i<n; i++){
books[i] = in.nextLine();
}
String str = in.nextLine();
in.close();
String[] keyWord = str.split(" ");
int count = 0;
for(int i=0; i<n; i++){//将没本书名与关键字进行匹配,
int tempValue = 0;
for(int j=0; j<keyWord.length; j++){
if(books[i].indexOf(keyWord[j])>-1){
tempValue++;//匹配值衡量书名和关键字的匹配程度,越大,匹配程度越高
}
}
if(tempValue>0){
count++;
fitValue = Arrays.copyOf(fitValue, count);
fitValue[count-1] = tempValue;
bookNo = Arrays.copyOf(bookNo, count);
bookNo[count-1] = i;
}
}
for(int i=0; i<fitValue.length-1; i++){//将匹配值从大到小排序
for(int j=0; j<fitValue.length-i-1; j++){
if(fitValue[j]<fitValue[j+1]){
int temp = fitValue[j];
fitValue[j] = fitValue[j+1];
fitValue[j+1] = temp;
temp = bookNo[j];
bookNo[j] = bookNo[j+1];
bookNo[j+1] = temp;
}else if(fitValue[j]==fitValue[j+1]){//在匹配值相同的情况下,按字母顺序排序
int lth;
if(books[bookNo[j]].length()<books[bookNo[j+1]].length()){
lth = books[bookNo[j]].length();
}else{
lth = books[bookNo[j+1]].length();
}
for(int k=0; k<lth; k++){
if(books[bookNo[j]].charAt(k)>books[bookNo[j+1]].charAt(k)){
int temp = bookNo[j];
bookNo[j] = bookNo[j+1];
bookNo[j+1] = temp;
break;
}
}
}
}
}
if(count<1){
return;
}else{
for(int i=0; i<bookNo.length; i++){
System.out.println(bookNo[i]);
System.out.println(books[bookNo[i]]);
}
}
}
}