Skip to content

Instantly share code, notes, and snippets.

@soeunkk
Last active September 17, 2022 11:01
Show Gist options
  • Save soeunkk/7487b98f637e2b62954f165593d16fbd to your computer and use it in GitHub Desktop.
Save soeunkk/7487b98f637e2b62954f165593d16fbd to your computer and use it in GitHub Desktop.
/*
* 김소은
* 과제2. 결제 금액 캐시백 계산 프로그램
*
* 캐시백과 관련된 상수, 함수를 묶어 클래스를 만들었습니다.
* 입력값이 잘못됐으면 재입력할 수 있도록 구현하였습니다.
*/
import java.util.InputMismatchException;
import java.util.Scanner;
class Cashback {
private static final float CASHBACK_RATIO = 0.1f; // 캐시백 비율
private static final int CASHBACK_UINT = 100; // 캐시백 단위
private static final int CASHBACK_LIMIT = 300; // 캐시백 한도
public static void printCashback(int price) {
int cashback = calculateCashback(price);
System.out.printf("결제 금액은 %d원이고, 캐시백은 %d원 입니다.\n", price, cashback);
}
public static int calculateCashback(int price) {
int cashback = (int)(price * CASHBACK_RATIO);
int cashbackCutting = (cashback / CASHBACK_UINT) * CASHBACK_UINT;
return Math.min(cashbackCutting, CASHBACK_LIMIT);
}
}
public class Test2 {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("[캐시백 계산]");
int price = inputPrice();
Cashback.printCashback(price);
closeResource();
}
private static int inputPrice() {
int price = 0;
boolean isValid = false;
while (! isValid) {
System.out.print("결제 금액을 입력해 주세요.(금액):");
try {
checkIntType();
price = scanner.nextInt();
checkValidPrice(price);
isValid = true;
} catch (InputMismatchException e) {
System.out.println(e.getMessage());
}
}
return price;
}
private static void checkIntType() {
if (! scanner.hasNextInt()) {
removeBuffer();
throw new InputMismatchException("숫자만 입력 가능합니다.");
}
}
private static void checkValidPrice(int price) {
if (price < 0) {
throw new InputMismatchException("결제 금액은 0원 이상이어야 합니다.");
}
}
private static void removeBuffer() { scanner.next(); }
private static void closeResource() { scanner.close(); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment