※ 사용자로부터 임의의 두 정수와 연산자를 입력받아 사칙연산을 수행하는 프로그램을 구현한다.
 단, 클래스와 인스턴스의 개념을 활용하여 작성할 수 있도록 한다.

 실행 예)
 임의의 두 정수 입력(공백 구분) : 10 5
 임의의 연산자 입력( + - * / )  : +
 >> 10 + 5 = 15
 계속하려면 아무 키나 누르세요...


import java.util.Scanner;
import java.io.IOException;

class Calculate
{
	char op;
	int n1,n2;

	/*
	// 생성자 → 사용자 정의 생성자가 없으면 디폴트 생성자가 삽입된다
	Calculate()
	{
		// 텅 비어 있는 상태
	}
	*/
	// 입력받을 메소드
	void input() throws IOException
	{
		Scanner sc = new Scanner(System.in);

		System.out.print("임의의 두 정수 입력(공백 구분) : ");
		n1 = sc.nextInt();
		n2 = sc.nextInt();
		
		System.out.print("임의의 연산자 입력( + - * / )  : ");
		op = sc.next().charAt(0);
		//op = (char)System.in.read();

	}

	// 연산을 수행할 메소드
	int cal()
	{
		int result = 0;
		
		if(op == '+')
			result = n1 + n2;
		else if(op == '-')
			result = n1 - n2;
		else if(op == '*')
			result = n1 * n2;
		else if(op == '/')
			result = n1 / n2;
		else
		{
			System.out.print("잘못된 연산자 입력\n");
			return 0;
		}
		return result;
	}

	void print(int result)
	{
		System.out.printf(">> %d %c %d = %d", n1, op, n2, result);
	}
}

public class Test075
{
	public static void main(String[] args) throws IOException
	{
		// Calculate 인스턴스 생성
		Calculate cc = new Calculate();

		// 입력 메소드 호출
		cc.input();

		// 연산 메소드 호출
		int result = cc.cal();

		// 결과 출력 메소드 호출
		cc.print(result);


	}
}

 

실행 결과

// 실행 결과
/*
임의의 두 정수 입력(공백 구분) : 10 5 
임의의 연산자 입력( + - * / )  : + 
>> 10 + 5 = 15 
계속하려면 아무 키나 누르세요...
*/

'JAVA > 클래스와 객체' 카테고리의 다른 글

Test077 생성자(2)  (0) 2020.09.05
Test076 생성자(1)  (0) 2020.09.05
Test074 클래스와 인스턴스(3)  (0) 2020.09.05
Test073 클래스와 인스턴스(2)  (0) 2020.09.05
Test072 클래스와 인스턴스(1)  (2) 2020.09.05

+ Recent posts