ArrayList應用案例二:課程信息的查詢

ArrayList應用案例二:課程信息的查詢

案例目的:加強 ArrayList 的使用
案例需求:在案例一的基礎之上,ᨀ示用戶“請輸入要查詢的關鍵字”,當用戶輸入關鍵字
後,可以按照課程名稱查詢出符合條件的課程

案例解析:
1. 這道題目的關鍵是 找到包含關鍵字(用戶輸入的),我們可以遍歷查找,並將其放入
一個新的列表,假定爲 new_list(就是這句話聲明的:ArrayList<Course> new_list = new 
ArrayList<Course>();)。
2. 如何判斷列表中的某一個元素是否包含關鍵字,這裏我們要用到字符串的 contains 方
法。所以,我們需要不斷的遍歷每一個課程對象,並且利用該方法判斷每一個課程對
象的課程名稱(course.getCname())是否包含關鍵字。如果包含,就將該課程放入 new_list
中。最後循環打印出來即可。

案例實現:

Course.java(課程類)

package www.yiniuedu.pojo;

/**
 * Course.java(課程類)
 * 
 * @author bsh
 *
 */
public class Course {
	private String cId;// 課程編號
	private String cName;// 課程名稱

	public Course() {
		super();
	}

	public Course(String cId, String cName) {
		super();
		this.cId = cId;
		this.cName = cName;
	}

	public String getcId() {
		return cId;
	}

	public void setcId(String cId) {
		this.cId = cId;
	}

	public String getcName() {
		return cName;
	}

	public void setcName(String cName) {
		this.cName = cName;
	}

	@Override
	public String toString() {
		return "課程信息 [課程編號=" + cId + ", 課程名稱=" + cName + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((cId == null) ? 0 : cId.hashCode());
		result = prime * result + ((cName == null) ? 0 : cName.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Course other = (Course) obj;
		if (cId == null) {
			if (other.cId != null)
				return false;
		} else if (!cId.equals(other.cId))
			return false;
		if (cName == null) {
			if (other.cName != null)
				return false;
		} else if (!cName.equals(other.cName))
			return false;
		return true;
	}

}

測試類:

TestOne.java(測試類)

package www.yiniuedu.test;

import java.util.ArrayList;
import java.util.Scanner;

import www.yiniuedu.pojo.Course;

public class TestOne {

	public static void main(String[] args) {

		Course c1 = new Course("j001","Java程序設計");
		Course c2 = new Course("c001","文學素養");
		Course c3 = new Course("m001","高等數學");
		Course c4 = new Course("e001","大學英語");
		ArrayList<Course> list = new ArrayList<Course>();
		list.add(c1);
		list.add(c2);
		list.add(c3);
		list.add(c4);
		System.out.println("請輸入要查詢的關鍵字:");
		Scanner sc = new Scanner(System.in);
		String key = sc.next();
		ArrayList<Course> new_List = new ArrayList<Course>();
		for(Course c:list) {
			if(c.getcName().contains(key)) {
				new_List.add(c);
			}
		}
		for(Course c:new_List) {
			System.out.println(c);
		}
		
	}

}

測試執行結果:

測試結果

創作不易,費時費力,小手輕點,順手打賞

微信打賞

微信掃碼打賞1元   

QQ打賞

QQ

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章