โปรแกรมจำลองการกินแอปเปิ้ล
โจทย์
Given the list of person and number of apples. Write a program to keep track of how many apples each person has at the end of the list.
The input is a list of pairs <person, number of apple> and the person which you have to return his/her remaining number of apples. The list ends when it reaches input of 0. Number of apple can be positive and negative. A positive integer means a person buys the given amount of apples. A negative integer means a person eats the given amount of apples.
This list of example means a person A buys 3 apples, a person B buys 3 apples, and a person A eats 2 apples. The list end when the input is 0. At the end the list provide you an input A which means it asks you how many apples does A have? In this case, A has 1 apple (i.e., buys 3 and eats 2).
Noted: Only one character is used to represent each person.
| Input | Output |
|---|---|
| A 3 B 3 A -2 0 A | 1 |
โค้ด
import java.util.HashMap;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
HashMap<Character, Integer> map = new HashMap<>();
while (true) {
String input = scanner.next();
if (input.equals("0")) break;
int amount = scanner.nextInt();
map.put(input.charAt(0), map.getOrDefault(input.charAt(0), 0) + amount);
}
char find = scanner.next().charAt(0);
System.out.println(map.get(find));
}
}คำอธิบาย
import java.util.HashMap; // สำหรับเก็บข้อมูลแบบ key-value
import java.util.Scanner; // สำหรับรับข้อมูลจากผู้ใช้1. การประกาศตัวแปรเริ่มต้น
Scanner scanner = new Scanner(System.in);
HashMap<Character, Integer> map = new HashMap<>();- สร้าง HashMap โดยใช้ Character เป็น key (ชื่อคน) และ Integer เป็น value (จำนวนแอปเปิ้ล)
2. การรับข้อมูลและประมวลผล
while (true) {
String input = scanner.next(); // รับชื่อคนหรือ 0
if (input.equals("0")) break; // ถ้ารับ 0 ให้ออกจากลูป
int amount = scanner.nextInt(); // รับจำนวนแอปเปิ้ล
map.put(input.charAt(0), // เก็บหรืออัพเดตจำนวนแอปเปิ้ล
map.getOrDefault(input.charAt(0), 0) + amount);
}การใช้ getOrDefault
map.getOrDefault(key, defaultValue)จะ:- คืนค่าที่มีอยู่แล้วถ้าเคยเจอ key นี้
- คืนค่า defaultValue (0 ในที่นี้) ถ้าไม่เคยเจอ key นี้
3. การแสดงผลลัพธ์
char find = scanner.next().charAt(0); // รับชื่อคนที่ต้องการตรวจสอบ
System.out.println(map.get(find)); // แสดงจำนวนแอปเปิ้ลของคนนั้นแผนภาพการทำงาน
ตัวอย่างการทำงาน
ตัวอย่างที่ 1: การซื้อและกินแอปเปิ้ล
Input:
A 3 // A ซื้อแอปเปิ้ล 3 ลูก
B 3 // B ซื้อแอปเปิ้ล 3 ลูก
A -2 // A กินแอปเปิ้ล 2 ลูก
0 // จบการรับข้อมูล
A // ต้องการทราบจำนวนแอปเปิ้ลของ A
การทำงานภายใน HashMap:
1. เริ่มต้น: {}
2. หลัง A 3: {A=3}
3. หลัง B 3: {A=3, B=3}
4. หลัง A -2: {A=1, B=3}
Output: 1