drexqq

[Java, 자바] 2진수, 10진수, 16진수 계산기 본문

공부노트/개인공부!

[Java, 자바] 2진수, 10진수, 16진수 계산기

drexqq 2020. 5. 26. 13:10
728x90
반응형

Java를 이용해서 2진수, 10진수, 16진수간에 서로 바꿀 수 있는 계산기를 만들어 보았다.

 

코드

package main;

import java.util.Scanner;

public class mainClass {

	public static void main(String[] args) {
		/*
		 	숫자 입력 -> 메뉴 번호
		 	
		 	1. 10진수를 2진수로 변환해서 출력
		 	2. 2진수를 10진수로 변환해서 출력
		 	3. 10진수를 16진수로 변환해서 출력
		 	4. 16진수를 10진수로 변환해서 출력
		 	5. 2진수를 16진수로 변환해서 출력
		 	6. 16진수를 2진수로 변환해서 출력
		 	7. 종료
		*/
		Scanner sc = new Scanner(System.in);
		
		// 메뉴 종류
		String menuArr[] = 
			{
				"10 to 2",
				"2 to 10",
				"10 to 16",
				"16 to 10",
				"2 to 16",
				"16 to 2",
				"END"
			};
		// 메뉴 선택
		out:while(true) {
			System.out.println("메뉴를 숫자로 선택해주세요.");
			for (int i = 0; i < menuArr.length; i++) {
				System.out.println((i + 1)+". "+menuArr[i]);
			}
			int menu = sc.nextInt();
			System.out.print(menuArr[menu-1]+" >> \n");	// 선택한 메뉴 노출
			String strNum = sc.next();	// 사용자가 입력할 숫자
			String result = "";
			int temp;
			if (menu == 1) {	// 10 to 2
				temp = Integer.parseInt(strNum);
				result = Integer.toBinaryString(temp);
			}
			else if (menu == 2) {	// 2 to 10
				temp = Integer.parseInt(strNum, 2);
				result = temp+"";
			}
			else if (menu == 3) {	// 10 to 16
				temp = Integer.parseInt(strNum);
				result = Integer.toHexString(temp);
			}
			else if (menu == 4) {	// 16 to 10
				temp = Integer.parseInt(strNum ,16);
				result = temp+"";
			}
			else if (menu == 5) {	// 2 to 16
				temp = Integer.parseInt(strNum, 2);
				result = Integer.toHexString(temp);
			}
			else if (menu == 6) {	// 16 to 2
				temp = Integer.parseInt(strNum, 16);
				result = Integer.toBinaryString(temp);
			}
			else if (menu == 7) {
				System.out.println(menuArr[menu-1]);
				break out;
			}
			System.out.println(menuArr[menu-1]+"의 결과는 "+result+"입니다 \n");
		}
	}

}

 

입력받은 메뉴에 해당하는 계산을 하기 위해 while문과 if문을 사용해서 만들어 보았다.

 

if문을 switch문으로 바꾸어도 좋을 것 같다.

728x90
반응형
Comments