카테고리 없음

#44 JAVA 오버로딩 계산기 문제

사재원 교수 2022. 5. 27. 20:58

처음으로 오버로딩이라는 개념이 나왔다.

오버로딩이란? 이름이 같은 메소드이지만 성분이 달라서 각기 다른 메소드로써 존재할수있게끔 하는 것을 말한다.

그니까 쉽게 말하면 Hi() 라는 메소드와 Hi(int a) 라는 메소드가 있다.

통상적으로 같은 이름의 메소드 변수 클래스 등은 사용할수없지.........만?

보다시피 안에 매개변수가 들어있는 Hi메소드와 매개변수가 없는 Hi메소드가 있다. 이로써 이름은 같을지라도 오버로딩이 되어있기에 서로 각자 다른 메소드로써 사용이 가능해진다. 매개변수의 수가 다르거나 매개변수의 자료형이 다르거나 등의 이유로 오버로딩이 가능하다.

 

내가 풀이한 코드를 한번 보자

package NewProject;

import java.util.Random;
import java.util.Scanner;

//정수 연산 , 실수 연산
class Coutroll{
	Scanner sc = new Scanner(System.in);

	public void hap(int a,int b,int c) { //정수 연산
		if(c==1) {
			System.out.println("결과 값 : " + (a+b));
		}else if(c==2) {
			System.out.println("결과 값 : " + (a-b));
		}else if(c==3) {
			System.out.println("결과 값 : " + (a*b));
		}else if(c==4) {
			System.out.println("결과 값 : " + (a/b));
		}
	}

	public void hap(double a,double b,int c) { //실수 연산
		if(c==1) {
			System.out.println("결과 값 : " + (double)(a+b));
		}else if(c==2) {
			System.out.println("결과 값 : " + (double)(a-b));
		}else if(c==3) {
			System.out.println("결과 값 : " + (double)(a*b));
		}else if(c==4) {
			System.out.println("결과 값 : " + (double)(a/b));
		}
	}


	public void start() {
		
		while(true) {
			System.out.print("1.정수연산 2.실수연산 3.종료 : ");
			int num = sc.nextInt();
			if(num == 1) { //정수연산
				int c;
				while(true) {
					System.out.print("1.더하기 2.빼기 3.곱하기 4.나누기 : ");
					c = sc.nextInt();//연산자 선택
					if(!(c < 0 || c > 4)) {
						break;
					}
				}
				System.out.print("숫자 1 입력 : ");
				int a = sc.nextInt();//숫자1
				System.out.print("숫자 2 입력 : ");
				int b = sc.nextInt();//숫자2
				hap(a,b,c);
			}else if(num == 2) {//실수연산
				int c;
				while(true) {
					System.out.print("1.더하기 2.빼기 3.곱하기 4.나누기 : ");
					c = sc.nextInt();//연산자 선택
					if(!(c < 0 || c > 4)) {
						break;
					}
				}
				System.out.print("숫자 1 입력 : ");
				double a = sc.nextInt();//숫자1
				System.out.print("숫자 2 입력 : ");
				double b = sc.nextInt();//숫자2
				hap(a,b,c);
			}else if(num == 3) {//종료
				System.out.println("프로그램 종료");
				break;
			}else {
				System.out.println("다시 입력 바람");
			}
		}
	}

}




public class Start {
	public static void main(String[] args) {

		Coutroll c = new Coutroll();
		c.start();

	}
}

hap이라는 메소드가 두개가 있는데 첫번째 hap메소드는 int 자료형만을 받아서 정수연산을 할수있게끔 하는 메소드이고

두번째 hap메소드는 double 자료형을 받아서 실수연산을 할수 있게끔 하는 메소드이다.

참고로 int a = 숫자 1 / int b = 숫자 2 / int c = 연산자기호 선택하는 숫자 이다.

중간중간 숫자를 선택할때 while문을 돌려서 올바른 숫자가 나오게끔 걸러냈다.

 

 

 

감사합니다.