JAVA 기초

JAVA 24

Vanillwa 2023. 9. 13. 20:28

 

계산기 구현해보기

package ex4_calculator;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Calculator extends Frame implements ActionListener {

	String[] sustr = { "7", "8", "9", "4", "5", "6", "1", "2", "3", "0", "+/-", "." };
	Button[] subt = new Button[sustr.length];

	String[] funstr = { "BackSpace", "CE", "C" };
	Button[] funbt = new Button[funstr.length];

	String[] operstr = { "+", "-", "*", "/" };
	Button[] operbt = new Button[operstr.length];

	Button equbt = new Button("=");

	Label disp = new Label("0.", Label.RIGHT);

	// true면 처음, false면 처음이 아님
	// 0이 연속으로 입력되는거를 방지
	boolean first = true;

	// false면 소수점 버튼을 누르지 않음
	boolean jumcheck = false;

	// 연산자
	char operator = '+';

	double result = 0;

	public Calculator() {
		super("Calculator");// 프레임의 제목
		buildGUI();// GUI 설계 메서드
		setEvent();//만든 기능을 객체에 붙여주는 메서드
	}

	// 각각의 버튼을 눌렀을 때 이벤트 처리
	@Override
	public void actionPerformed(ActionEvent e) {

		// 숫자입력 로직
		for (int i = 0; i < subt.length - 2; i++) {
			if (e.getSource() == subt[i]) {
				// 처음으로 눌렀는지
				if (first) {
					if (disp.getText().equals("0.") && subt[i].getLabel().equals("0")) {
						return;// 함수를 빠져나가는 return
					}

					disp.setText(subt[i].getLabel() + ".");
					first = false;
				} else { // 처음으로 누른게 아닌경우
					String tmp = disp.getText();
					if (jumcheck) { // "."버튼을 누른적이 있다.
						disp.setText(tmp + subt[i].getLabel());
					} else {
						tmp = tmp.substring(0, tmp.length() - 1);
						disp.setText(tmp + subt[i].getLabel() + ".");
					}
				}
				return;
			}
		}
		// 부호 로직 처리하기
		if (e.getSource() == subt[subt.length - 2]) {
			String tmp = disp.getText();
			if (tmp.equals("0.")) {
				return;
			}
			if (tmp.charAt(0) == '-') {
				disp.setText(tmp.substring(1));
			} else {
				disp.setText('-' + tmp);
			}
		}
		
		//소수점 처리 로직
		if(e.getSource()==subt[subt.length-1]) {
			first = false;
			jumcheck = true;
			return;
		}
		
		// 연산자 처리 로직
		for (int i = 0; i < operbt.length; i++) {
			if (e.getSource() == operbt[i]) {
				calc();
				operator = operbt[i].getLabel().charAt(0);
				first = true;
				jumcheck = false;
			}
		}
		// = 처리 로직
		if (e.getSource() == equbt) {
			calc();
			first = true;
			jumcheck = false;
			operator = '+';
			result = 0;
			return;
		}
		// backspace 로직 처리
		if (e.getSource() == funbt[0]) {
			String tmp = disp.getText();
			if (tmp.equals("0."))
				return;

			// 한자리수 숫자일때
			if (tmp.length() == 2) {
				disp.setText("0.");
				first = true;
				jumcheck = false;
				return;
			}

			// 한자리수 음수일때
			if (tmp.length() == 3 && tmp.charAt(0) == '-') {
				disp.setText("0.");
				first = true;
				jumcheck = false;
				return;
			}

			// 0이하의 소수점
			if (tmp.length() == 3 && tmp.charAt(0) == '0') {
				disp.setText("0.");
				first = true;
				jumcheck = false;
				return;
			}

			// 두자리 이상의 숫자일때
			if (tmp.charAt(tmp.length() - 1) == '.') {
				tmp = tmp.substring(0, tmp.length() - 2);
				disp.setText(tmp + ".");
			} else {
				disp.setText(tmp.substring(0, tmp.length() - 1));
			}
			return;
		}

		// CE (Clear Entry) : 가장 최근에 추가된 데이터만 삭제
		if (e.getSource() == funbt[1]) {
			disp.setText("0.");
			first = true;
			jumcheck = false;
			result = 0;
			return;
		}

		// C (Clear)
		if (e.getSource() == funbt[2]) {
			disp.setText("0.");
			first = true;
			jumcheck = false;
			operator = '+';
			result = 0;
			return;
		}
	} // actionPerformed();

	public void calc() {
		double value = Double.parseDouble(disp.getText());
		switch (operator) {
		case '+':
			result += value;
			break;
		case '-':
			result -= value;
			break;
		case '*':
			result *= value;
			break;
		case '/':
			result /= value;
			break;
		}
		// 소수점 처리
		Double val = result - (int) result;

		if (val > 0) {
			disp.setText(String.valueOf(result));
		} else {
			disp.setText(String.valueOf((int) result + "."));
		}
	} // calc();
	
	//이벤트 연결
	public void setEvent() {
		for(int i=0;i<subt.length;i++) {
			subt[i].addActionListener(this);
		}
		
		for(int i=0;i<funbt.length;i++) {
			funbt[i].addActionListener(this);
		}
		
		for(int i=0;i<operbt.length;i++) {
			operbt[i].addActionListener(this);
		}
		
		equbt.addActionListener(this);
	}

	// 화면구성
	public void buildGUI() {
		setBackground(Color.CYAN);

		// 상하좌우 여백
		add("North", new Label());
		add("South", new Label());
		add("West", new Label());
		add("East", new Label());

		Panel mainPanel = new Panel(new BorderLayout(3, 3));
		disp.setBackground(Color.white);
		disp.setFont(new Font("Serif", Font.BOLD, 15));
		mainPanel.add("North", disp);

		Panel cPanel = new Panel(new GridLayout(1, 2, 3, 3));

		// 숫자 배치 패널
		Panel cleftPanel = new Panel(new GridLayout(4, 3, 3, 3));
		for (int i = 0; i < subt.length; i++) {
			subt[i] = new Button(sustr[i]);
			subt[i].setFont(new Font("Serif", Font.BOLD, 15));
			cleftPanel.add(subt[i]);
		}

		cPanel.add(cleftPanel);

		// 기능 배치 패널
		Panel crightPanel = new Panel(new GridLayout(4, 1, 3, 3));

		Panel cr1Panel = new Panel(new GridLayout(1, 3, 3, 3));
		for (int i = 0; i < funbt.length; i++) {
			funbt[i] = new Button(funstr[i]);
			funbt[i].setFont(new Font("Serif", Font.BOLD, 15));
			cr1Panel.add(funbt[i]);
		}

		crightPanel.add(cr1Panel);

		Panel cr2Panel = new Panel(new GridLayout(1, 3, 3, 3));
		Panel cr3Panel = new Panel(new GridLayout(1, 3, 3, 3));

		for (int i = 0; i < operstr.length; i++) {
			operbt[i] = new Button(operstr[i]);
			operbt[i].setFont(new Font("Serif", Font.BOLD, 15));

			if (i < 2) {
				cr2Panel.add(operbt[i]);
			} else {
				cr3Panel.add(operbt[i]);
			}
		}

		crightPanel.add(cr2Panel);
		crightPanel.add(cr3Panel);

		equbt.setFont(new Font("Serif", Font.BOLD, 15));

		crightPanel.add(equbt);

		cPanel.add(crightPanel);

		mainPanel.add("Center", cPanel);

		add("Center", mainPanel);

		pack();

		Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension my = getSize();
		setLocation(scr.width / 2 - my.width / 2, scr.height / 2 - my.height / 2);

		setResizable(false);
		setVisible(true);

		this.addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}// buildGUI();

	public static void main(String[] args) {
		new Calculator();
	}
}

 

 

 

실행 결과

우리가 일반적으로 알고있는 계산기다

 


 

'JAVA 기초' 카테고리의 다른 글

JAVA 23-2  (0) 2023.09.12
JAVA 23-1  (0) 2023.09.12
JAVA 22-2  (0) 2023.09.12
JAVA 22-1  (0) 2023.09.12
JAVA 21-2  (0) 2023.09.08