图书录入与检索

要求从控制台输入需录入的书数目,然后依次输入书名。最后输入搜索关键字,从录入的书中检索匹配该关键字的书,并打印书名和索书号。优先按照匹配程度的顺序打印,其次按照字母顺序。实现代码如下:

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]]);
			}
		}
	
	}
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值