Back-End/수업 내용 응용 연습장
[java] 계산기 (개별 입력, 정수)
Dev-RiQ
2024. 12. 3. 10:59
학원 1달차 (11월 말)
조건문 / 반복문 / 배열 / 이차원배열 / 문자열 학습 응용
+ 구글 클래스, 메소드 검색 후 기본 습득
가장 많이 본게 sum 메소드 만들기라 가장 먼저 떠오른 계산기 제작 도전!
만들어 놓고 보니 쓸데 없이 뭘 많이 적은 느낌
숫자 항목이 3개 이상일때 복잡함 방지를 위해 연산자 기준으로 뒷 값을 b에 넣는 식으로 했으면 좋았을듯..!
package 깔짝;
import java.util.Scanner;
public class _002Calc개별입력 {
public static int sum(int a, int b) {
return a + b;
}
public static int min(int a, int b) {
return a - b;
}
public static int mul(int a, int b) {
return a * b;
}
public static double div(int a, int b) {
return a / b;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int calc = 0;
String input = "";
int cnt = 0;
double rs = 0;
String save = "";
while (true) {
System.out.print("입력 >> ");
input = sc.next();
save += input + " ";
if (input.equals("=")) {
System.out.println(save);
System.out.println("답 : " + rs);
break;
}
if (input.charAt(0) < 58 && input.charAt(0) > 47) {
if (cnt % 2 == 0) {
a = Integer.parseInt(input);
} else {
b = Integer.parseInt(input);
}
if (cnt != 0) {
if (cnt % 2 == 0) {
c = b;
d = a;
} else {
c = a;
d = b;
}
if (calc == 42) {
rs = mul(c, d);
} else if (calc == 43) {
rs = sum(c, d);
} else if (calc == 45) {
rs = min(c, d);
} else if (calc == 47) {
rs = div(c, d);
}
if (cnt % 2 == 0) {
a = (int) rs;
} else {
b = (int) rs;
}
}
cnt++;
continue;
} else if (input.charAt(0) == 42) { // *
calc = 42;
continue;
} else if (input.charAt(0) == 43) { // +
calc = 43;
continue;
} else if (input.charAt(0) == 45) { // -
calc = 45;
continue;
} else if (input.charAt(0) == 47) { // /
calc = 47;
continue;
}
}
sc.close();
}
}