### **TIL - 2025.03.12**
## **오늘 배운 것 개요**
- **Java Enum 활용**: 사용자 유형별 할인율 적용
- **파일 입출력 적용**: 사용자별 잔액 및 포인트 관리
- **코드 최적화**: `Math.max()`, `AtomicInteger`, `Stream API` 활용
---
## **1. Kiosk 프로젝트 - 결제 및 사용자 데이터 관리 개선**
### **1. 사용자별 잔액 및 포인트 관리 (파일 입출력)**
- 기존 **고정된 변수 방식**에서 **파일을 활용한 데이터 저장 방식**으로 개선
- `UserData` 클래스를 활용하여 **사용자의 잔액 및 포인트를 저장하고 불러옴**
#### **코드 개선**
```java
public class UserData {
private static final String DIRECTORY = "UserData/";
public static int[] loadUserData(String userId) {
Properties users = new Properties();
String fileName = DIRECTORY + userId + ".properties";
File file = new File(fileName);
if (!file.exists()) {
System.out.println(userId + "님 신규 등록되었습니다. (가입 포인트: 1,000 지급)");
saveUserData(userId, 0, 1000);
return new int[]{0, 1000};
}
try (FileInputStream fileInput = new FileInputStream(file)) {
users.load(fileInput);
int cash = Integer.parseInt(users.getProperty("cash", "0"));
int point = Integer.parseInt(users.getProperty("point", "1000"));
return new int[]{cash, point};
} catch (IOException e) {
e.printStackTrace();
return new int[]{0, 1000};
}
}
public static void saveUserData(String userId, int cash, int point) {
Properties user = new Properties();
String fileName = DIRECTORY + userId + ".properties";
user.setProperty("cash", String.valueOf(cash));
user.setProperty("point", String.valueOf(point));
try (FileOutputStream fos = new FileOutputStream(fileName)) {
user.store(fos, "User Data (cash, point)");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
**개선된 점**
- **사용자별 데이터 파일 관리** (`userId.properties` 파일에 잔액 및 포인트 저장)
- **신규 사용자 자동 등록** (`파일이 없으면 기본 값 설정 후 저장`)
- **유지보수 용이** (`변수 대신 파일에서 데이터 로드 가능`)
---
### **2. 결제 시 잔액 부족 예외 처리 및 포인트 적립**
- **사용자 잔액이 부족한 경우 결제 차단**
- **결제 후 1% 포인트 적립**
#### **코드 개선**
```java
public void payment(Scanner sc, PayType payType, int totalPrice, String userId) {
System.out.println("=====================");
System.out.println(payType.getPaytypes() + "로 결제를 진행합니다.");
int[] userData = UserData.loadUserData(userId);
int userCash = userData[0];
int userPoint = userData[1];
System.out.println("적립 포인트를 사용하시겠습니까?\nYES: 1, NO: 2");
int discountPoint = 0;
if (sc.hasNextInt()) {
int input = sc.nextInt();
sc.nextLine();
if (input == 1) {
System.out.println("몇 포인트를 사용하시겠습니까?\n보유포인트: " + userPoint);
discountPoint = sc.nextInt();
if (discountPoint < 1000 || discountPoint > totalPrice || discountPoint > userPoint) {
System.out.println("잘못된 포인트 사용입니다.");
return;
}
userPoint -= discountPoint;
} else if (input != 2) {
System.out.println("**입력값을 확인해 주세요");
return;
}
}
int finalAmount = totalPrice - discountPoint;
if (payType == PayType.CASH && userCash < finalAmount) {
System.out.println("잔액이 부족합니다.");
return;
}
int pointEarned = (int) (finalAmount * 0.01);
userPoint += pointEarned;
System.out.println("=======[결제창]=======");
System.out.println(" 금액: " + totalPrice);
System.out.println("사용 포인트: " + discountPoint);
System.out.println("최종 결제액: " + finalAmount);
System.out.println("---------------------");
System.out.println("적립 포인트: " + pointEarned);
System.out.println("현재 포인트: " + userPoint);
System.out.println("=====================");
System.out.println("결제가 완료되었습니다.");
UserData.saveUserData(userId, userCash - finalAmount, userPoint);
}
```
**개선된 점**
- **잔액 부족 예외 처리 추가** (`userCash < finalAmount` 검사 후 결제 차단)
- **포인트 적립 기능 추가** (`결제 금액의 1% 적립`)
- **최종 사용자 데이터 저장 개선** (`파일에 반영되도록 수정`)
---
## **오늘의 결론**
1. **파일 입출력을 활용하여 사용자 데이터를 관리**
2. **Enum을 활용하여 할인율을 효과적으로 관리**
3. **잔액 부족 예외 처리 및 포인트 적립 기능 추가**
---
## **다음 학습 목표**
- **람다 & 스트림을 활용하여 결제 프로세스 최적화**
- **테스트 코드 작성하여 프로그램 안정성 검증**
'TIL' 카테고리의 다른 글
[TIL]네트워크 기본 개념과 Web 지식 (0) | 2025.05.14 |
---|---|
[TIL]2차원 배열 연산 (0) | 2025.05.14 |
[TIL]Enum 활용 (0) | 2025.05.14 |
[TIL]예외 처리 개선 (0) | 2025.05.14 |
[TIL]객체 지향 원칙과 코드 리팩토 (0) | 2025.05.14 |