Math.max(), AtomicInteger, Stream API 활용UserData 클래스를 활용하여 사용자의 잔액 및 포인트를 저장하고 불러옴 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 파일에 잔액 및 포인트 저장)파일이 없으면 기본 값 설정 후 저장)변수 대신 파일에서 데이터 로드 가능)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% 적립) 파일에 반영되도록 수정)