프로그래밍 언어/javastudy

자바 공부 #2 지폐, 동전 개수 출력 프로그램(코드가 더러울 땐 구글링)

fladi 2021. 7. 4. 22:47
728x90

이번에도 명품 Java Essential교재 연습문제입니다. 

Scanner와 if문 연습을 위한 문제인데요.

돈의 액수를 입력받아 오만원권부터 1원까지 각각 몇 개로 변환되는지 출력하라는 문제입니다.

 

 

어려운 문제는 아니지만 구글링의 중요성을 위해 블로그에 올려봅니다. 

저는 처음 문제를 풀었을 때 상당히 코드가 더럽다고 생각했었습니다. 실제로 제 코드는 더러운 게 맞았고요.

다음은 제가 처음 문제를 풀었을 때 코드입니다.

 

import java.util.Scanner;

public class money {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		int money;
		int fiftythousand, tenthousand, thousand, fivehundred;
		int hundred, ten, one;
		
		System.out.println("돈의 액수를 입력하세요>> ");
		money = scanner.nextInt();
		
		fiftythousand = money/50000;
		tenthousand = (money%50000)/10000;
		thousand = ((money%50000)%10000)/1000;
		fivehundred = (((money%50000)%10000)%1000)/500;
		hundred = ((((money%50000)%10000)%1000)%500)/100;
		ten = (((((money%50000)%10000)%1000)%500)%100)/10;
		one = (((((money%50000)%10000)%1000)%500)%100)%10;
		
		System.out.print("오만원 "+fiftythousand+"개, ");
		System.out.print("만원 "+tenthousand+"개, ");
		System.out.print("천원 "+thousand+"개, ");
		System.out.print("500원 "+fivehundred+"개, ");
		System.out.print("100원 "+hundred+"개, ");
		System.out.print("10원 "+ten+"개, ");
		System.out.print("1원 "+one+"개");
		
		scanner.close();
	}

}

 

딱 봐도 너무 보기 어렵고 얼타다 잘못적으면 고치기도 너무 어려웠습니다다. 괄호 짝 맞추는 게 상당히 힘들더라고요.

저는 보기좋은 코드가 좋은 코드라고 배웠습니다. 그래서 더 나은 알고리즘을 찾아 구글링을 해봤습니다.

 

 

세상에는 저와 비슷한 문제를 훨씬 깔끔하게 푼 사람들이 정말 많았습니다ㅠㅠ 

다음은 구글링하여 깔끔한 알고리즘을 알아낸 뒤 다시 코딩한 저의 코드입니다.

 

import java.util.Scanner;

public class money {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		int money;
		int fiftythousand, tenthousand, thousand,
			fivehundred, hundred, ten, one;
		int temp;
		
		System.out.println("돈의 액수를 입력하세요>> ");
		money = scanner.nextInt();
		temp = money;
		
		fiftythousand = temp/50000;
		temp %= 50000;
		tenthousand = temp/10000;
		temp %= 10000;
		thousand = temp/1000;
		temp %= 1000;
		fivehundred = temp/500;
		temp %= 500;
		hundred = temp/100;
		temp %= 100;
		ten = temp/10;
		temp %= 10;
		one = temp;
		
		System.out.print("오만원 "+fiftythousand+"개, ");
		System.out.print("만원 "+tenthousand+"개, ");
		System.out.print("천원 "+thousand+"개, ");
		System.out.print("500원 "+fivehundred+"개, ");
		System.out.print("100원 "+hundred+"개, ");
		System.out.print("10원 "+ten+"개, ");
		System.out.print("1원 "+one+"개");
		
		scanner.close();
	}

}

 

(코드는 위에 것과 거의 똑같지만 여기선 money값을 보존하고 싶어서 temp라는 임시변수를 만들어줬습니다)

딱 봐도 너무 깔끔해진 것 같습니다. 

 

 

역시 코딩은 구글링인 것 같습니다. 좋은 알고리즘이 너무 많네요!! 저는 배우는 입장이니 열심히 구글링하면서 살아야겠습니다.

728x90