국비학원 10일차 : 환전 프로세스

Digeut·2023년 3월 8일
0

국비학원

목록 보기
10/44

환전 어플리케이션

Input

넣을 화폐 단위 / 바꿀 화폐 단위 / 돈

Process

☆입력 다 받았는지 확인!!
돈이 들어왔는지(0보다 커야함)
입력한 화폐가 동일할 때
우리가 관리하는 화폐단위에 속해있는지(넣은돈과 바꿀돈 모두)

원화 대비 엔화 환율 (프로세스 상에 필요)
원화 대비 달러 환율
달러 대비 엔화 환율
기준이 중요!! 데이터베이스 배워야한다

Output

(정상인 경우에 대한 출력) // 비정상에 대한 출력도 정해놔야한다.

비정상일때 (입력의 검증에 대한 아웃풋)

  • 모두 입력하지 않았을때 "모두 입력해 주세요" 출력
  • 입력한 금액이 동일한 화폐일때 "동일한 화폐로 환전할 수 없습니다" 출력
  • 입력한 금액이 '-' 혹은 0일때 "유효한 금액이 아닙니다"출력
  • 관리하고 있지 않은 화폐종류일때 "유효한 화폐가 아닙니다"출력

정상일때
돈 - 화폐

ExchangeApplication

import java.util.Scanner;

// 환전기 어플리케이션
// Input : 금액, 넣을 화폐, 바꿀 화폐
// Output : 금액, 바뀐 화폐
public class ExchangeApplication {
	
	//🟡화폐단위 따로 관리해주기, 관리하는 화폐 배열로 만들어줌
	private static String[] managedCurrencies = {
			"KRW", "USD", "JPY"
	};
	
	//원화, 달러, 엔화만 환전 가능하게함. 
    //가능한 경우의 수 6, 6개짜리 배열 만들기
	private static ExchangeRate[] exchangeRates = { 
    //가져와서 바로 초기화 해주는건가? //인스턴스
    //ExchangeRate 클래스를 따로 만들어서 생성자 생성후
    //가져와 초기화 시킨것
		// 원화 - 달러
		new ExchangeRate("KRW","USD", 1000 / 1318.80),
		// 원화 - 엔
		new ExchangeRate("KRW","JPY", 1000 / 960.35),
		// 달러 - 원화
		new ExchangeRate("USD", "KRW", 1318.80 / 1000),
		// 달러 - 엔
		new ExchangeRate("USD", "JPY", 1318.80 / 0.96035),
		// 엔 - 원화
		new ExchangeRate("JPY", "KRW", 960.35 / 1000),
		// 엔 - 달러
		new ExchangeRate("JPY", "USD", 0.96035 / 1318.80)
	};
	
	
	public static void main(String[] args) { 
    	//인스턴스 변수 가져와서 쓸수없다(static 사용했으므로)
		//ExchangeRate exchangeRate = new ExchangeRate();
		//ExchangeRate에 private를 해놨기때문에 사용할 수없게된다.
		
		//입력받기
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("넣을 화폐 : ");
		String exchangingCurrency = scanner.nextLine(); //넣을 화폐 단위 
		
		System.out.println("바꿀 화폐 : ");
		String exchangedCurrency = scanner.nextLine(); // 바꿀 화폐 단위 
		
		System.out.println("금액 : ");
		int amount = scanner.nextInt(); // 돈
		
		//입력값 확인
		System.out.println(exchangingCurrency + " " + exchangedCurrency + " " + amount);
		
		
		//입력 검증
		// 1️⃣⭐모두 입력했는지
		if(exchangingCurrency.isBlank() || exchangedCurrency.isBlank()){
			System.out.println("모두 입력해 주세요.");
			return; //메서드 종료
		}
		
		// 2️⃣입력한 화폐가 동일 할때
		if(exchangingCurrency.equals(exchangedCurrency)) {
			System.out.println("동일한 화폐로 환전할 수 없습니다");
			return;
		}
		
		// 3️⃣유효한 금액이 아닐 때 (금액이 양수가 아닐때)
		if(amount <= 0) {
			System.out.println("유효한 금액이 아닙니다");
			return;
		}
		
		// 4️⃣관리하고 있는 화폐단위가 아닐 때
        //저장공간 휘발성 메모리에 있다
		// 맨위에 저장한 managedCurrencies에 저장 
        //→ SQL문으로 처리하면 더 쉽게할수 있다.(🔴~🔴구간 한줄로 처리된다)

//		if(!exchangingCurrency.equals("KRW") || !exchangedCurrency.equals("KRW")) {
//			//이렇게 다 하나하나 조건에 넣으려면 하드하다.. 나중에 수정도 어려워진다
//			//우리가 관리하는 화폐단위를 따로 관리해주면 좋다 
//			→ 🟡맨위에 배열만들어서 묶어서 관리
//		}
		
        //⭐배열을 읽을 용도로만 쓰려면 foreach 형태가 더 좋다
		//실제로 수정을 하거나 입력을 하려는 경우 일반 for문을 사용해야 한다
		
			
//			오류떠서 주석처리
		//if(
//					!exchangingCurrency.equals(exchangedCurrency)|| 
//					!exchangedCurrency.equals(exchangingCurrency)
//					){
//				System.out.println("유효하지 않은 화폐 단위입니다.");
//				return;
//			}
//		}
		
		🔴boolean hasExchanging = false;
		boolean hasExchanged = false;
		
        //foreach문
		for(String managedCurrency : managedCurrencies) {
			if( exchangingCurrency.equals(managedCurrency) ) {
				hasExchanging = true;
			}
			if(exchangedCurrency.equals(exchangedCurrency)) {
            //왜 둘다 ed ed 비교일까
				hasExchanged = true;
			}
		}
		
		if(!(hasExchanging && hasExchanged)) {
			System.out.println("유효하지 않은 화폐단위입니다.");
			return;
		🔴}
		
		
		//정상 프로세스
		//휘발성 메모리로 저장해놓은 것을 가져와서 작업
		//데이터 베이스에 저장을 해두면 코드가 훨씬 단순해지고 한줄로 끝난다.
		double resultAmount = amount;
		
//		for(ExchangeRate exchangeRate : exchangeRates) {
//			if(exchangingCurrency.equals(exchangeRate.getExchangingCurrency())) {
//			if(exchangedCurrency.equals(exchangeRate.getExchangedCurrency())) {					
//				}
//			}
//		} 
		//이런식의 구조를 피라미드 구조라고 하는데 
        //이렇게 되면 복잡하고 보기가 어려워진다.
		//if문 두개를 합쳐서 한번에 보이게 하는 구조로 
        //하는게 한눈에 보기 더 좋다
		
		for(ExchangeRate exchangeRate : exchangeRates) {
			boolean ⭐isSame =
            	exchangingCurrency.equals(exchangeRate.getExchangingCurrency()) && 			
            	exchangedCurrency.equals(exchangeRate.getExchangedCurrency()); 
                //구문깔끔하게
			if(⭐isSame){
				resultAmount *= exchangeRate.getExchangeRate();
				break; //break 넣는 이유🤔
				}
			}
		
		//정상 출력하기
		System.out.println(exchangedCurrency + " : " + resultAmount);
	}

}

ExchangeRate

// 화폐 : 화폐 = 환율
// 환율 관리할 용도의 클래스
public class ExchangeRate {
	
	//넣을 화폐 (ex. 원화, 달러, 엔화, 위안화 ... )
	private/*캡슐화?*/ String exchangingCurrency ; 
    //💡왜 굳이 캡슐화하는거지
	//바꿀 화폐 (ex. 원화, 달러, 엔화, 위안화 ... )
	private String exchangedCurrency ;
	// 환율 ( 1000 / 1,316.30(원화 대비 달러) )
	private double exchangeRate ;
	
	//이클립스에서 오른쪽버튼 source 구간에서 다 만든것... 
    //다 타이핑할 필요없이 만들수 있다(🟢~🟢구간)
    //source - Generate Constructer~
	🟢public ExchangeRate(String exchangingCurrency, 
    			String exchangedCurrency, double exchangeRate) {
//		super();
		this.exchangingCurrency = exchangingCurrency;
		this.exchangedCurrency = exchangedCurrency;
		this.exchangeRate = exchangeRate;
	}
	//source - Generate Getter and Setter~
	public String getExchangingCurrency() {
		return exchangingCurrency;
	}

	public void setExchangingCurrency(String exchangingCurrency) {
		this.exchangingCurrency = exchangingCurrency;
	}

	public String getExchangedCurrency() {
		return exchangedCurrency;
	}

	public void setExchangedCurrency(String exchangedCurrency) {
		this.exchangedCurrency = exchangedCurrency;
	}

	public double getExchangeRate() {
		return exchangeRate;
	}

	public void setExchangeRate(double exchangeRate) {
		this.exchangeRate = exchangeRate;
	}

	@Override //출력을 해보고 싶을때 사용? 인스턴스.toString 해서 쓰면 된다
    //source - toString()~
	public String toString() {
		return "ExchangeRate [exchangingCurrency =" 
        + exchangingCurrency + ", exchangedCurrency=" 
        + exchangedCurrency
		+ ", exchangeRate=" + exchangeRate + "]";
	🟢}
	
	//생성자
//	public ExchangeRate(
//			String exchangingCurrency, 
//			String exchangedCurrency, 
//			double exchangeRate) { 
		//인스턴스와 매개변수 이름 같을때 this 써서 초기화
//		this.exchangingCurrency = exchangingCurrency;
//		this.exchangedCurrency = exchangedCurrency;
//		this.exchangeRate = exchangeRate;
//	}
	
	//💡Get, Set 사용하는 이유
    //get, set 메서드 : private로 설정해뒀기때문에 접근 가능하도록 함
	//Get :  해당 인스턴스에 특정 인스턴스 변수(이미 갖고 있는것)를 반환해주는 메서드
	// 인스턴스가 가지고 있는 특정 인스턴스 변수의 값을 반환해주기 위한 메서드
	// 반환타입 메서드명(get~특정인스턴스변수이름) (매개변수) 
    // 여기서 매개변수는 빈칸 → 필요한것 없다. 있는걸 반환해주는것이라서
    
    //get은 인스턴스를 생성해야하고 
    //set은 인스턴스를 생성하고 나서 쓰는것..?🤔
    
    //Get메서드
//	public/*외부에서 접근할수 있어야 하므로*/ String getExchangingCurrency() { 
//		return this.exchangingCurrency;
//	}
//	public String getExchangedCurrency() {
//		return this.exchangedCurrency;
//	}
//	public double getExchangeRate() {
//		return this.exchangeRate;
//	}
	
	
	//Set : 원래 갖고 있는 인스턴수 변수를 변경해주는 메서드 
    //반환은 하지 않는다. 변경만 함. 반환하지 않으니 반환타입은 void 
	//void 메서드명(:set~매개변수명)(매개변수)
    //매개변수는 바꾸고자하는 값,위에 선언한 인스턴스 타입과 변수 그대로 입력
	//인스턴스가 가지고 있는 특정 인스턴스 변수를 변경할 때 사용하는 메서드
    
    //Set메서드
//	public/*외부에서 접근할수 있어야 하므로*/ void 
				setExchangingCurrency(String exchangingCurrency) {
//		this.exchangingCurrency = exchangingCurrency;
//	}
//	public void setExchangedCurrency (String exchangedCurrency) {
//		this.exchangedCurrency = exchangedCurrency;
//	}
//	public void setExchangeRate (double exchangeRate) {
//		this.exchangeRate = exchangeRate;
//	}
}

💡캡슐화 하는 이유

캡슐화 : 관련이 있는 변수와 함수를 하나의 클래스로 묶고 외부에서 쉽게 접근하지 못하도록 은닉하는 것. 캡슐화를 통해 응집도를 높인다.
객체에 직접적인 접근을 막고 외부에서 내부에 직접적으로 접근해 정보를 변경하지 못하도록 하면서 객체가 제공하는 필드와 메서드만을 통해서만 접근이 가능하도록 한다.

캡슐화를 하는 가장 큰 이유는 정보 은닉에 있다.
객체가 제공하는 필드와 메소드를 통해서만 접근이 가능하다.
객체 내의 정보 손상과 오용을 방지하고 데이터가 변경되어도
다른 객체에 영향을 주지 않아 독립성이 좋다.
캡슐화는 접근제어자를 통해 이루어진다.
출처 : https://defacto-standard.tistory.com/51

💡Get, Set 메서드 사용하는 이유

캡슐화 이후 public으로 지정된 getter setter을 사용한다.
메서드를 통해서 은닉된 객체를 접근 가능하게 한다.

Get

해당 인스턴스에 특정 인스턴스 변수(이미 갖고 있는것)를 반환해주는 메서드

public String getExchangingCurrency/*get특정인스턴스변수이름*/(매개변수는 비워둠)
	return this.exchangingCurrency;//반환 값

Set

원래 갖고 있는 인스턴수 변수를 변경해주는 메서드, 반환은 하지 않는다.
변경만 함. 그래서 반환 타입이 void

public void setExchangingCurrency/*get특정인스턴스변수이름*/
							(String exchangingCurrency)
	this.exchangingCurrency = exchangingCurrency;//반환 타입

get은 인스턴스를 생성하는 것이고 set은 인스턴스를 생성하고 나서 쓰는것?
get은 값 리턴, set은 값 저장

profile
개발자가 될 거야!

0개의 댓글