iT邦幫忙

2026 iThome 鐵人賽

DAY 10
0
自我挑戰組

Java 程式設計與實作:30 天打造個人記帳系統系列 第 26 篇

搜尋消費紀錄:用關鍵字快速找到花費

  • 分享至 

  • xImage
  •  

昨天 Day 25 完成了「依日期查詢」,現在可以輸入日期,找出當天的消費紀錄。

不過隨著記帳資料越來越多,我又想到另一個問題。

假設現在已經有很多紀錄:

2026-09-28|早餐|60 元|飲食
2026-09-28|捷運|30 元|交通
2026-09-29|咖啡|80 元|飲食
2026-09-30|午餐|150 元|飲食
2026-10-01|電影|300 元|娛樂
2026-10-02|咖啡|65 元|飲食

如果我突然想知道:

最近到底買了幾次咖啡?

一筆一筆看就很麻煩。

所以 Day 26 要加入 「關鍵字搜尋」,讓使用者只要輸入:

咖啡

程式就可以自動找出所有包含「咖啡」的消費紀錄。

今天要學 contains()

今天最重要的新語法是:

contains()

contains() 可以用來判斷一段 String 裡面,有沒有包含某個文字。

先看簡單的例子:

String item = "星巴克咖啡";
if (item.contains("咖啡")) {
System.out.println("找到了!");
}

結果:

找到了!

因為:

星巴克咖啡
↑
包含「咖啡」

所以:

item.contains("咖啡")

會得到:

true

如果搜尋:

item.contains("捷運")

結果就是:

false

第一步:加入搜尋功能

今天建立新的 Method:

public static void searchByKeyword()

先讓使用者輸入關鍵字:

System.out.print("請輸入搜尋關鍵字:");
String keyword =
scanner.nextLine();

例如:

請輸入搜尋關鍵字:咖啡

現在:

keyword

裡面就是:

咖啡

第二步:檢查每一筆 Expense

和昨天一樣,我們需要檢查 ArrayList 裡面的所有資料:

for (int i = 0;
i < expenses.size();
i++) {
Expense expense =
expenses.get(i);
}

接著取得每一筆消費的項目:

expense.getItem()

例如:

早餐
捷運
星巴克咖啡
電影
便利商店咖啡

第三步:使用 contains()

判斷:

if (
expense.getItem()
.contains(keyword)
)

假設:

keyword = 咖啡

程式就會依序檢查:

早餐 contains 咖啡
→ false
捷運 contains 咖啡
→ false
星巴克咖啡 contains 咖啡
→ true ✓
電影 contains 咖啡
→ false
便利商店咖啡 contains 咖啡
→ true ✓

最後就能找到兩筆紀錄。

第四步:顯示搜尋結果

找到之後:

System.out.println(
expense.getDate()
+ "|"
+ expense.getItem()
+ "|"
+ expense.getAmount()
+ " 元|"
+ expense.getCategory()
);

結果可能是:

===== 搜尋結果 =====
2026-09-29|星巴克咖啡|80 元|飲食
2026-10-02|便利商店咖啡|65 元|飲食

第五步:統計搜尋結果

和昨天一樣,我希望搜尋完不只是顯示資料,也順便統計。

建立:

int count = 0;
int total = 0;

找到一筆:

count++;
total += expense.getAmount();

假設:

星巴克咖啡 80 元
便利商店咖啡 65 元

最後:

count = 2
total = 145

就可以顯示:

找到 2 筆紀錄
合計支出:145 元

完整 searchByKeyword()

今天最重要的新 Method:

public static void searchByKeyword() {
System.out.println();
System.out.println(
"===== 關鍵字搜尋 ====="
);
System.out.print(
"請輸入搜尋關鍵字:"
);
String keyword =
scanner.nextLine();
int count = 0;
int total = 0;
System.out.println();
System.out.println(
"===== 搜尋結果 ====="
);
for (int i = 0;
i < expenses.size();
i++) {
Expense expense =
expenses.get(i);
if (
expense.getItem()
.contains(keyword)
) {
System.out.println(
expense.getDate()
+ "|"
+ expense.getItem()
+ "|"
+ expense.getAmount()
+ " 元|"
+ expense.getCategory()
);
count++;
total +=
expense.getAmount();
}
}
if (count == 0) {
System.out.println(
"找不到符合的消費紀錄。"
);
} else {
System.out.println();
System.out.println(
"找到 "
+ count
+ " 筆紀錄"
);
System.out.println(
"合計支出:"
+ total
+ " 元"
);
}
}

今天修改主選單

昨天:

  1. 新增消費
  2. 查看紀錄
  3. 查看總支出
  4. 分類支出統計
  5. 刪除消費紀錄
  6. 修改消費紀錄
  7. 設定預算
  8. 查看預算狀況
  9. 依日期查詢
  10. 離開

今天加入:

  1. 關鍵字搜尋
  2. 離開

所以變成:

===== 個人記帳系統 =====

  1. 新增消費
  2. 查看紀錄
  3. 查看總支出
  4. 分類支出統計
  5. 刪除消費紀錄
  6. 修改消費紀錄
  7. 設定預算
  8. 查看預算狀況
  9. 依日期查詢
  10. 關鍵字搜尋
  11. 離開

Switch 也加入:

case 10:
searchByKeyword();
break;
case 11:
running = false;
System.out.println(
"已離開個人記帳系統!"
);
break;

Day 26 完整程式

import java.util.Scanner;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDate;
class Expense {
private LocalDate date;
private String item;
private int amount;
private String category;
Expense(
LocalDate date,
String item,
int amount,
String category
) {
this.date = date;
this.item = item;
this.amount = amount;
this.category = category;
}
public LocalDate getDate() {
return date;
}
public String getItem() {
return item;
}
public int getAmount() {
return amount;
}
public String getCategory() {
return category;
}
public void setItem(String item) {
this.item = item;
}
public void setAmount(int amount) {
if (amount >= 0) {
this.amount = amount;
}
}
public void setCategory(String category) {
this.category = category;
}
}
public class Main {
static Scanner scanner =
new Scanner(System.in);
static ArrayList expenses =
new ArrayList<>();
static int budget = 0;
public static void main(String[] args) {
loadExpenses();
boolean running = true;
while (running) {
showMenu();
try {
System.out.print("請選擇功能:");
int choice =
scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
addExpense();
break;
case 2:
showExpenses();
break;
case 3:
calculateTotal();
break;
case 4:
categoryStatistics();
break;
case 5:
deleteExpense();
break;
case 6:
editExpense();
break;
case 7:
setBudget();
break;
case 8:
checkBudget();
break;
case 9:
searchByDate();
break;
case 10:
searchByKeyword();
break;
case 11:
running = false;
System.out.println(
"已離開個人記帳系統!"
);
break;
default:
System.out.println(
"沒有這個選項!"
);
}
} catch (InputMismatchException e) {
System.out.println(
"輸入錯誤,請輸入數字!"
);
scanner.nextLine();
}
}
scanner.close();
}
public static void showMenu() {
System.out.println();
System.out.println(
"===== 個人記帳系統 ====="
);
System.out.println("1. 新增消費");
System.out.println("2. 查看紀錄");
System.out.println("3. 查看總支出");
System.out.println("4. 分類支出統計");
System.out.println("5. 刪除消費紀錄");
System.out.println("6. 修改消費紀錄");
System.out.println("7. 設定預算");
System.out.println("8. 查看預算狀況");
System.out.println("9. 依日期查詢");
System.out.println("10. 關鍵字搜尋");
System.out.println("11. 離開");
}
public static void addExpense() {
System.out.println();
System.out.println(
"===== 新增消費 ====="
);
LocalDate today =
LocalDate.now();
System.out.print(
"請輸入消費項目:"
);
String item =
scanner.nextLine();
System.out.print(
"請輸入消費金額:"
);
int amount =
scanner.nextInt();
String category =
chooseCategory();
Expense expense =
new Expense(
today,
item,
amount,
category
);
expenses.add(expense);
saveExpenses();
System.out.println(
"記帳成功!"
);
System.out.println(
"日期:" + today
);
}
public static String chooseCategory() {
System.out.println();
System.out.println(
"請選擇消費分類:"
);
System.out.println("1. 飲食");
System.out.println("2. 交通");
System.out.println("3. 購物");
System.out.println("4. 娛樂");
System.out.print(
"請輸入選項:"
);
int choice =
scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
return "飲食";
case 2:
return "交通";
case 3:
return "購物";
case 4:
return "娛樂";
default:
return "其他";
}
}
public static void showExpenses() {
System.out.println();
System.out.println(
"===== 消費紀錄 ====="
);
if (expenses.size() == 0) {
System.out.println(
"目前沒有消費紀錄。"
);
return;
}
for (int i = 0;
i < expenses.size();
i++) {
Expense expense =
expenses.get(i);
System.out.println(
(i + 1) + ". "
+ expense.getDate()
+ "|"
+ expense.getItem()
+ "|"
+ expense.getAmount()
+ " 元|"
+ expense.getCategory()
);
}
}
public static void calculateTotal() {
int total = 0;
for (int i = 0;
i < expenses.size();
i++) {
total +=
expenses.get(i).getAmount();
}
System.out.println();
System.out.println(
"===== 支出統計 ====="
);
System.out.println(
"目前共有 "
+ expenses.size()
+ " 筆消費"
);
System.out.println(
"總支出:"
+ total
+ " 元"
);
}
public static void categoryStatistics() {
int foodTotal = 0;
int transportTotal = 0;
int shoppingTotal = 0;
int entertainmentTotal = 0;
for (int i = 0;
i < expenses.size();
i++) {
Expense expense =
expenses.get(i);
switch (
expense.getCategory()
) {
case "飲食":
foodTotal +=
expense.getAmount();
break;
case "交通":
transportTotal +=
expense.getAmount();
break;
case "購物":
shoppingTotal +=
expense.getAmount();
break;
case "娛樂":
entertainmentTotal +=
expense.getAmount();
break;
}
}
System.out.println();
System.out.println(
"===== 分類支出統計 ====="
);
System.out.println(
"飲食:" + foodTotal + " 元"
);
System.out.println(
"交通:" + transportTotal + " 元"
);
System.out.println(
"購物:" + shoppingTotal + " 元"
);
System.out.println(
"娛樂:"
+ entertainmentTotal
+ " 元"
);
}
public static void deleteExpense() {
System.out.println();
System.out.println(
"===== 刪除消費紀錄 ====="
);
if (expenses.size() == 0) {
System.out.println(
"目前沒有可以刪除的紀錄。"
);
return;
}
showExpenses();
System.out.print(
"請輸入要刪除的紀錄編號:"
);
int number =
scanner.nextInt();
scanner.nextLine();
if (
number >= 1
&& number <= expenses.size()
) {
Expense deleted =
expenses.remove(
number - 1
);
saveExpenses();
System.out.println(
"已刪除:"
+ deleted.getItem()
);
} else {
System.out.println(
"沒有這筆紀錄!"
);
}
}
public static void editExpense() {
System.out.println();
System.out.println(
"===== 修改消費紀錄 ====="
);
if (expenses.size() == 0) {
System.out.println(
"目前沒有可以修改的紀錄。"
);
return;
}
showExpenses();
System.out.print(
"請輸入要修改的紀錄編號:"
);
int number =
scanner.nextInt();
scanner.nextLine();
if (
number >= 1
&& number <= expenses.size()
) {
Expense expense =
expenses.get(
number - 1
);
System.out.print(
"請輸入新的消費項目:"
);
String item =
scanner.nextLine();
System.out.print(
"請輸入新的消費金額:"
);
int amount =
scanner.nextInt();
String category =
chooseCategory();
expense.setItem(item);
expense.setAmount(amount);
expense.setCategory(category);
saveExpenses();
System.out.println(
"修改成功!"
);
} else {
System.out.println(
"沒有這筆紀錄!"
);
}
}
public static void setBudget() {
System.out.println();
System.out.println(
"===== 設定預算 ====="
);
System.out.print(
"請輸入預算金額:"
);
budget =
scanner.nextInt();
scanner.nextLine();
System.out.println(
"預算設定成功:"
+ budget
+ " 元"
);
}
public static void checkBudget() {
System.out.println();
System.out.println(
"===== 預算狀況 ====="
);
if (budget <= 0) {
System.out.println(
"尚未設定預算。"
);
return;
}
int total = 0;
for (int i = 0;
i < expenses.size();
i++) {
total +=
expenses.get(i)
.getAmount();
}
System.out.println(
"目前預算:"
+ budget
+ " 元"
);
System.out.println(
"目前支出:"
+ total
+ " 元"
);
if (total > budget) {
int over =
total - budget;
System.out.println(
"已超出預算 "
+ over
+ " 元!"
);
} else {
int remaining =
budget - total;
System.out.println(
"剩餘預算:"
+ remaining
+ " 元"
);
}
}
public static void searchByDate() {
System.out.println();
System.out.println(
"===== 依日期查詢 ====="
);
System.out.print(
"請輸入查詢日期(YYYY-MM-DD):"
);
String input =
scanner.nextLine();
try {
LocalDate searchDate =
LocalDate.parse(input);
int total = 0;
int count = 0;
System.out.println();
System.out.println(
"===== "
+ searchDate
+ " 消費紀錄 ====="
);
for (int i = 0;
i < expenses.size();
i++) {
Expense expense =
expenses.get(i);
if (
expense.getDate()
.equals(searchDate)
) {
System.out.println(
expense.getItem()
+ "|"
+ expense.getAmount()
+ " 元|"
+ expense.getCategory()
);
total +=
expense.getAmount();
count++;
}
}
if (count == 0) {
System.out.println(
"這一天沒有消費紀錄。"
);
} else {
System.out.println();
System.out.println(
"當日共有 "
+ count
+ " 筆消費"
);
System.out.println(
"當日總支出:"
+ total
+ " 元"
);
}
} catch (Exception e) {
System.out.println(
"日期格式錯誤,請使用 YYYY-MM-DD。"
);
}
}
public static void searchByKeyword() {
System.out.println();
System.out.println(
"===== 關鍵字搜尋 ====="
);
System.out.print(
"請輸入搜尋關鍵字:"
);
String keyword =
scanner.nextLine();
int count = 0;
int total = 0;
System.out.println();
System.out.println(
"===== 搜尋結果 ====="
);
for (int i = 0;
i < expenses.size();
i++) {
Expense expense =
expenses.get(i);
if (
expense.getItem()
.contains(keyword)
) {
System.out.println(
expense.getDate()
+ "|"
+ expense.getItem()
+ "|"
+ expense.getAmount()
+ " 元|"
+ expense.getCategory()
);
count++;
total +=
expense.getAmount();
}
}
if (count == 0) {
System.out.println(
"找不到符合的消費紀錄。"
);
} else {
System.out.println();
System.out.println(
"找到 "
+ count
+ " 筆紀錄"
);
System.out.println(
"合計支出:"
+ total
+ " 元"
);
}
}
public static void saveExpenses() {
try {
FileWriter writer =
new FileWriter(
"expenses.txt"
);
for (int i = 0;
i < expenses.size();
i++) {
Expense expense =
expenses.get(i);
writer.write(
expense.getDate()
+ ","
+ expense.getItem()
+ ","
+ expense.getAmount()
+ ","
+ expense.getCategory()
+ "\n"
);
}
writer.close();
} catch (IOException e) {
System.out.println(
"檔案儲存失敗!"
);
}
}
public static void loadExpenses() {
try {
File file =
new File(
"expenses.txt"
);
Scanner fileScanner =
new Scanner(file);
while (
fileScanner.hasNextLine()
) {
String line =
fileScanner.nextLine();
String[] data =
line.split(",");
if (data.length == 4) {
LocalDate date =
LocalDate.parse(
data[0]
);
String item =
data[1];
int amount =
Integer.parseInt(
data[2]
);
String category =
data[3];
Expense expense =
new Expense(
date,
item,
amount,
category
);
expenses.add(
expense
);
}
}
fileScanner.close();
System.out.println(
"記帳資料讀取成功!"
);
} catch (Exception e) {
System.out.println(
"目前沒有已儲存的記帳資料。"
);
}
}
}

實際測試

假設目前有:

===== 消費紀錄 =====

  1. 2026-09-29|星巴克咖啡|80 元|飲食
  2. 2026-09-30|捷運|30 元|交通
  3. 2026-10-01|電影|300 元|娛樂
  4. 2026-10-02|便利商店咖啡|65 元|飲食
  5. 2026-10-02|午餐|150 元|飲食

選擇:

請選擇功能:10

輸入:

===== 關鍵字搜尋 =====
請輸入搜尋關鍵字:咖啡

結果:

===== 搜尋結果 =====
2026-09-29|星巴克咖啡|80 元|飲食
2026-10-02|便利商店咖啡|65 元|飲食
找到 2 筆紀錄
合計支出:145 元

這樣就能快速知道自己最近在「咖啡」上花了多少錢。

搜尋不到資料時

假設輸入:

請輸入搜尋關鍵字:機票

如果沒有任何相關紀錄:

===== 搜尋結果 =====
找不到符合的消費紀錄。

這樣比什麼都不顯示更清楚。

contains() 和 equals() 有什麼不同?

昨天使用:

equals()

今天使用:

contains()

兩個看起來有點像,但功能不一樣。

假設:

String item = "星巴克咖啡";

如果:

item.equals("咖啡")

結果:

false

因為:

星巴克咖啡 ≠ 咖啡

但:

item.contains("咖啡")

結果:

true

因為「星巴克咖啡」裡面有包含「咖啡」。

所以可以簡單記:

equals()
→ 完全一樣嗎?
contains()
→ 裡面有包含嗎?

這也是為什麼搜尋功能比較適合使用 contains()。

今天的程式邏輯

今天的搜尋流程可以整理成:

使用者輸入「咖啡」
↓
取得 keyword
↓
使用 for 檢查所有 Expense
↓
expense.getItem()
↓
contains(keyword)
↓
┌────┴────┐
true false
↓ ↓
顯示紀錄 跳過
↓
count++
total += amount
↓
最後顯示搜尋結果

Day 26 學習心得

今天完成了關鍵字搜尋功能,學到 String 的 contains() 方法。之前的 equals() 是判斷內容是否完全相同,而 contains() 可以判斷一段文字中有沒有包含指定的關鍵字,所以很適合拿來做搜尋。

這次也再次使用 ArrayList、for 迴圈和 if 條件判斷,逐筆檢查所有 Expense。找到符合的資料後,不只顯示紀錄,也順便計算筆數和總金額。

做到今天,我發現前面學到的很多基礎語法並不是學完就結束,而是在後面的功能中一直重複使用。現在記帳系統已經可以依日期查詢,也可以利用關鍵字搜尋,查找資料比之前方便很多。


上一篇
依日期查詢:找出指定日期的所有消費
下一篇
消費分析:找出最高與最低的一筆支出
系列文
Java 程式設計與實作:30 天打造個人記帳系統 共 30 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言