이 기사는 Java에서 계산기를 작성하는 일반적인 방법을 요약합니다. 다음과 같이 참조에 대해 공유하십시오.
방법 1 : 방법 1
패키지 wanwa; import java.awt.*; import java.awt.event.*; import javax.swing.*; 공개 클래스 계산기는 jframe {개인 gridbaglayout 레이아웃; private jtextfield 디스플레이 필드; // community resulation double; // // // commund string; // 계산 저장 결과 개인 부울 시작; // 숫자 공개 계산기 () {super ( "calculator"); 컨테이너 = getContentPane (); getContentPane (); getContentPane (); jtextfield (20); displayfield.sethorizontalalignment (jtextfield.right); 제한자 .gridx = 0; 제한자 .gridy = 0; ronstraints.gridwidth = 4; chanstraints.gridheight = 1; constraints.fill = gridbagconstrints.both; constraints.weights = 100; constraints. 100; layout.setConstraints (DisplayField, 제약 조건); 컨테이너 .add (DisplayField); ActionListener insert = new InsertAction (); ActionListener Command = new CommentAction (); // addButton ( "백 스페이스", 0, 1, 2, 1, instbutton ( "CE", 2, 1, 1, 1, insert); // insert); // insert); 1, 1, 삽입); addButton ( "7", 0, 2, 1, 1, insert); addButton ( "8", 1, 2, 1, 1, 삽입); addButton ( "9", 2, 2, 1, 1, 1, 삽입); AddButton ( "/", 3, 2, 1, 1, 1, 명령); AddButton ( "4", 1, 1, 1, 1, 1, 1, 1 삽입); addButton ( "5", 1, 3, 1, AddButton ( "6", 2, 3, 1, 1, 1, insert); addButton ( "*", 3, 3, 1, 1, 명령); AddButton ( "1", 0, 4, 1, 1, 삽입); AddButton ( "2", 1, 4, 1, 1, insert); 1, insert); addButton ( "-", 3, 4, 1, 1, 1, 명령); addButton ( "0", 0, 5, 1, 1, insert); // addButton ( "+/-", 1, 5, 1, 1, 1, 1, 삽입); // "-"부호 ","+"는 실용적인 값이 없다 (", 2, 1, 1, 1, 1, 1 삽입); addButton ( "+", 3, 5, 1, 1, 명령); addButton ( "=", 0, 6, 4, 1, 명령); this.setResizable (false); setSize (180, 200); setVisible (true);} private void addButton (string label, int row, int column, int with, int height, actionlistener listener) {jbutton button = new jbutton (label); constraints.gridx = row; constratt.gridwidtats.gridwidtats. = height; restraints.fill = gridbagconstraints.both; button.addactionListener (리스너); Layout.setConstraints (버튼, 제약 조건); 컨테이너.add (button);} 개인 클래스 인서 actaction ActionListener {public void actionPerformed (ActionInEvent event) {String Input = event.getActionCommand (); if (시작); {displayfield.settext ( ""); start = false; if (input.equals ( "+/-")) displayfield.settext (displayfield.getText ()+"-");} if (! input.equals ( "+/-"))) {if (input.equals ( "backspace")) {string str =); displayfield.settext (str.substring (0, str.length () -1));} else if (input.equals ( "ce") || input.equals ( "c")) {displayfield.settext ( "0"); true;} elsedisplayfield.settext (displayfield.settext ()}}}}}}}}}}}}}}}}} public void ActionPerformed (ActionEvent evt) {String Command = evt.getActionCommand (); if (start) {lastCommand = 명령; } else {계산 (double.parsEdouble (displayfield.getText ())); LastCommand = 명령; start = true; }}} public void calculate (double x) {if (lastcommand.equals ( " +")) 결과 += x; else ( " -")) 결과 -= x; else (lastCommand.equals ( " *")) result *= x; else (lastCommand.equals ( " /"))) x; displayfield.settext ( "" + result);} public static void main (String [] args) {계산기 계산 = 새 계산기 (); calculator.setDefaultCloseOperation (jframe.exit_on_close);}}방법 2 : 방법 2.
import java.awt.*; import java.awt.event.*; public class mycalculator {private frame f; Private TextField TF = New Textfield (30); 사적인 긴 결과; 개인 부울 부록 = 거짓; 개인 숯 사업자 = '='; 개인 버튼 [] BTN = 새 버튼 [15]; public mycalculator () {initcomponent (); } private void initComponent () {f = 새 프레임 ( "내 계산기 v1.0"); F.setLayout (New BorderLayout ()); // 프레임은 BorderLayout F.AddWindowListener (새 WindowAdapter () {public void WindowClosing (WindowEvent evt) {System.exit (0);}})를 사용합니다. 패널 센터 패널 = 새로운 패널 (); CenterPanel.SetLayout (New GridLayout (5, 3)); // 패널은 gridlayout numberlistener nl = new numberlistener ()를 사용합니다. OperatorListener OL = New OperatorListener (); BTN [10] = 새 버튼 ( "+"); btn [11] = 새 버튼 ( "-"); BTN [12] = 새 버튼 ( "*"); BTN [13] = 새 버튼 ( "/"); BTN [14] = 새 버튼 ( "="); for (int i = 0; i <= 9; i ++) {btn [i] = 새 버튼 (string.valueof (i)); centerpanel.add (btn [i]); btn [i] .addactionListener (nl); if (i%2 == 1) {centerpanel.add (btn [(i+19)/2]); btn [(i+19)/2] .addactionListener (ol); }} f.add (CenterPanel, BorderLayout.Center); 패널 NorthPanel = 새 패널 (); tf.seteditable (false); Northpanel.add (Tf); f.add (Northpanel, Borderlayout.north); } public void go () {f.pack (); F. 세트 Visible (true); } public static void main (String [] args) {new mycalculator (). go (); } /***내부 클래스 메소드를 사용하여 클래스 내 메인 클래스의 내부 멤버에 대한 액세스를 용이하게하기 위해 리스너 인터페이스를 구현합니다. *이 클래스는 번호 버튼의 액션 이벤트의 청취 및 처리를 담당합니다.*/ 클래스 번호 리스트너는 ActionListener {public void actionPerformed (ActionEvent e) {if (! append) {tf.settext ( ""); 부록 = true; } string s = tf.getText (); s+= e.getActionCommand (); tf.settext (들); if (! btn [10] .isenabled ()) {for (int i = 10; i <= 14; i ++) btn [i] .setenabled (true); }}} / *** 멤버 내부 클래스, 운영자 버튼의 이벤트 처리를 담당하는 멤버 내부 클래스* / 클래스 OPERATORLISTENE는 ActionListener {public void ActionPerformed (ActionEvent e) {if (! 부록) return; for (int i = 10; i <= 14; i ++) btn [i] .setenabled (false); 문자열 s = tf.getText (); long num = long.parselong (s); // 텍스트 필드 수를 얻습니다. // Append Switch (연산자) {case '+': result+= num; break; 사례 '-': 결과-= num; break; 사례 '*': 결과*= num; break; CASE '/': {if (num == 0) result = 0; else result/= num; 부서지다; } case '=': result = num; break; } tf.settext (string.valueof (결과)); // 결과 값을 TextField String Op = e.getActionCommand ()로 설정합니다. 연산자 = op.charat (0); // 연산자 세트}}}메소드 3 :
package wanwa;import java.util.*;public class calc {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("******************************");System.out.println("*/t/t/t/t/t/t*");System.out.println("* Instructions for use: 1. Addition 2. Subtraction 3. Multiplication 4. Division*");System.out.println("*/t/t/t/t/t/t*");System.out.println("***************************************************************");for(int i = 0; i <100; i ++) {System.out.print ( "/nplease :"); int num = input.nextInt (); 스위치 (num) {case 1 : system.out.println ( "/n ****** addite *******/n"); system.out.print ( "첫 번째 애드더를 입력하십시오 :"); int jiashu1 = input.nextint (); system.out.print ( "두 번째 애드더를 입력하십시오 :") 작업 결과 : " + jiashu1 +" + " + jiashu1 +"= "=" + (jiashu1 + jiashu2)); break; case 2 : system.out.println ( "/n ****** 당신은 sectraction *******/n"; system.out.print를 선택했습니다. input.nextint (); system.out.print ( "subtraction을 입력하십시오 :"); int jianshu2 = input.nextint (); system.out.println ( " + jianshu1 +" - " + jianshu2 +"= " + (jianshu1 -jianshu2)); 선택된 곱셈 *******/n "); system.out.print ("첫 번째 요소를 입력하십시오 : "); int chengfa1 = input.nextint (); system.out.print ("두 번째 요소를 입력하십시오 : "); int chengfa2 = input.nextint (); system.out.println (" + chengfa1 + " + chengfa1 +" + chengfa1 + " + chengfa1 +" + chengfa1 + " + chengfa1 (chengfa1*chengfa2)); break; case 4 : system.out.println ( "/n ****** 당신은 divisor를 입력하십시오 :"); double chufa1 = input.nextint (); system.out.print ( "divid chufa2 ="); input.nextint (); system.out.println ( "작동 결과는" + chufa1 + " /" + chufa2 + "=" + (chufa1 / chufa2) + "yu" + (chufa1 % chufa2)); break; default : system.out.println ( " / nyour 선택이 잘못되었다. 다시 선택! "); break;}}}}Method 4:
패키지 wanwa; import java.awt.*; import java.awt.event.*; import javax.swing.*; 공개 클래스 계산기는 jframe {개인 gridbaglayout 레이아웃; private jtextfield 디스플레이 필드; // community resulation double; // // // commund string; // 계산 저장 결과 개인 부울 시작; // 숫자 공개 계산기 () {super ( "calculator"); 컨테이너 = getContentPane (); getContentPane (); getContentPane (); jtextfield (20); displayfield.sethorizontalalignment (jtextfield.right); 제한자 .gridx = 0; 제한자 .gridy = 0; ronstraints.gridwidth = 4; chanstraints.gridheight = 1; constraints.fill = gridbagconstrints.both; constraints.weights = 100; constraints. 100; layout.setConstraints (DisplayField, 제약 조건); 컨테이너 .add (DisplayField); ActionListener insert = new InsertAction (); ActionListener Command = new CommentAction (); // addButton ( "백 스페이스", 0, 1, 2, 1, instbutton ( "CE", 2, 1, 1, 1, insert); // insert); // insert); 1, 1, 삽입); addButton ( "7", 0, 2, 1, 1, insert); addButton ( "8", 1, 2, 1, 1, 삽입); addButton ( "9", 2, 2, 1, 1, 1, 삽입); AddButton ( "/", 3, 2, 1, 1, 1, 명령); AddButton ( "4", 1, 1, 1, 1, 1, 1, 1 삽입); addButton ( "5", 1, 3, 1, AddButton ( "6", 2, 3, 1, 1, 1, insert); addButton ( "*", 3, 3, 1, 1, 명령); AddButton ( "1", 0, 4, 1, 1, 삽입); AddButton ( "2", 1, 4, 1, 1, insert); 1, insert); addButton ( "-", 3, 4, 1, 1, 1, 명령); addButton ( "0", 0, 5, 1, 1, insert); // addButton ( "+/-", 1, 5, 1, 1, 1, 1, 삽입); // "-"부호 ","+"는 실용적인 값이 없다 (", 2, 1, 1, 1, 1, 1 삽입); addButton ( "+", 3, 5, 1, 1, 명령); addButton ( "=", 0, 6, 4, 1, 명령); this.setResizable (false); setSize (180, 200); setVisible (true);} private void addButton (string label, int row, int column, int with, int height, actionlistener listener) {jbutton button = new jbutton (label); constraints.gridx = row; constratt.gridwidtats.gridwidtats. = height; restraints.fill = gridbagconstraints.both; button.addactionListener (리스너); Layout.setConstraints (버튼, 제약 조건); 컨테이너.add (button);} 개인 클래스 인서 actaction ActionListener {public void actionPerformed (ActionInEvent event) {String Input = event.getActionCommand (); if (시작); {displayfield.settext ( ""); start = false; if (input.equals ( "+/-")) displayfield.settext (displayfield.getText ()+"-");} if (! input.equals ( "+/-"))) {if (input.equals ( "backspace")) {string str =); displayfield.settext (str.substring (0, str.length () -1));} else if (input.equals ( "ce") || input.equals ( "c")) {displayfield.settext ( "0"); true;} elsedisplayfield.settext (displayfield.settext ()}}}}}}}}}}}}}}}}} public void ActionPerformed (ActionEvent evt) {String Command = evt.getActionCommand (); if (start) {lastCommand = 명령; } else {계산 (double.parsEdouble (displayfield.getText ())); LastCommand = 명령; start = true; }}} public void calculate (double x) {if (lastcommand.equals ( " +")) 결과 += x; else ( " -")) 결과 -= x; else (lastCommand.equals ( " *")) result *= x; else (lastCommand.equals ( " /"))) x; displayfield.settext ( "" + result);} public static void main (String [] args) {계산기 계산 = 새 계산기 (); calculator.setDefaultCloseOperation (jframe.exit_on_close);}}이 기사가 모든 사람의 Java 프로그래밍에 도움이되기를 바랍니다.