프로그래밍 언어 복습/JAVA
#20 JAVA 계산기 함수화하여 만들기
사재원 교수
2022. 5. 19. 20:05
package hihihi;
import java.util.Scanner;
class start{
Scanner sc = new Scanner(System.in);
int num;
//1. 주고 받고 (더하기)
public int hap(int a,int b) {
this.num = a + b;
return this.num;
}
//2. 안주고 받고 (곱)
public void gup(int a,int b) {
this.num = a*b;
}
//3. 주고 안받고 (빼기)
public int minus() {
int a = sc.nextInt();
int b = sc.nextInt();
int mus = a - b;
return mus;
}
//4. 안주고 안받고 (나누기)
public void div() {
int a = sc.nextInt();
int b = sc.nextInt();
int div = a / b;
System.out.println(div);
}
}
public class gta {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0);
start s = new start();
if(c=='+') {
int a = sc.nextInt();
int b = sc.nextInt();
int hap = s.hap(a, b);
System.out.println(hap);
}else if(c=='*') {
int a = sc.nextInt();
int b = sc.nextInt();
s.gup(a, b);
System.out.println(s.num);
}else if(c=='-') {
int a = s.minus();
System.out.println(a);
}else if(c=='/') {
s.div();
}
}
}
여기서 처음으로 메소드라는 개념이 나온다.
- 메소드는 입력값이 있고, 그 입력값을 받아서 무언가 한 다음 결과를 도출해 내는 수학의 함수와 비슷한 개념이다.
더하기 곱하기 빼기 나누기를 각각 만들어서 해보았는데 main에서 연산자기호를 받고 그거에 따라 메소드를 각기 다르게 실행하게끔 코드를 작성했다. 메소드의 형태에는 4가지가 존재한다.
1) 주고받고
2) 안주고받고
3) 주고 안받고
4) 안주고안받고
이 4가지를 전부 표현해보았다.
감사합니다.