[Java] 계산기 프로그램 구현_if문

JTI·2022년 10월 10일
0

📌 Code list

목록 보기
15/55
post-thumbnail

간단한 계산기 프로그램을 작성하여 보자.
먼저 사용자로부터 하나의 문자(+ / - ...)를 입력받고 사용자로부터 2개의 숫자를 입력받는다.

✏️ char로 문자기호 생성

import java.util.Scanner;

public class Calculator {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.print("연산을 입력하세요: ");
		char cal = sc.nextLine().charAt(0); // char 변수 입력받기
		
		System.out.print("피연산자 2개를 입력하세요: ");
		double x = sc.nextDouble();
		double y = sc.nextDouble();
	
		System.out.print(x + "*" + y + "= ");
		if (cal == '+') {
			System.out.println(x + y);
		} else if (cal == '-') {
			System.out.println(x - y);
		} else if (cal == '*') {
			System.out.println(x * y);
		} else if (cal == '/') {
			System.out.println(x / y);
		}
		
	}

}

char를 이용하여 사용자가 입력받은 기호를 비교하여 계산을 표출할 수 있다.

✏️ String으로 문자기호 생성

import java.util.Scanner;

public class Calculator {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.print("연산을 입력하세요: ");
		String cal = sc.next(); // String 변수 입력받기
		
		System.out.print("피연산자 2개를 입력하세요: ");
		double x = sc.nextDouble();
		double y = sc.nextDouble();
	
		System.out.print("");
		if (cal.equals("+")) { // equals 메서드로 문자 비교
			System.out.println(x + y);
		} else if (cal.equals("-")) {
			System.out.println(x - y);
		} else if (cal.equals("*")) {
			System.out.println(x * y);
		} else if (cal.equals("/")) {
			System.out.println(x / y);
		}
	}
}

String은 문자열을 나타냄으로 equals 메서드를 통해 문자를 비교할 수 있다.

📌 equals 메서드에 대한 자세한 내용
https://velog.io/@jipark09/Java-String-%EB%B9%84%EA%B5%90%EB%B0%A9%EB%B2%95equals

profile
Fill in my own colorful colors🎨

0개의 댓글