В этой статье суммируются общие методы написания калькуляторов на Java. Поделитесь этим для вашей ссылки, следующим образом:
Метод 1:
Пакет Wanwa; импорт java.awt.*; import java.awt.event.*; import javax.swing.*; Calculator Public Class Calculator Extends jframe {частный контейнер контейнер; частный схема Gridbaglayout; частная строка Сохранить Результат расчета Private Boolean Start; // Определить, является ли это началом численного общедоступного калькулятора () {Super ("Calculator"); Container = getContentPane (); Layout = new Gridbaglayout (); контейнер.setlayout (layout); ограничения = new Gridbonstraints (); start = ruptemant = 0; JTextField (20); DisplayField.SethorizontalAlignment (jtextfield.right); ограничения. Gridx = 0; ограничения. Gridy = 0; ограничения. GridWidth = 4; ограничения. GridHeight = 1; ограничения. 100; Layout.SetConstraints (DisplayField, ограничения); Container.Add (Displayfield); actionListener insert = new InsertAction (); actionListener Command = New CommandAction (); // addButton («BackSpace», 0, 1, 2, 1, INSERT); // AddButton («CE», 1, 1, 1, 1, INSERT); 1, вставка); addbutton ("7", 0, 2, 1, 1, вставка); addbutton ("8", 1, 2, 1, 1, вставка); addbutton ("9", 2, 2, 1, 1, вставка); Addbutton ("/", 3, 1, 1, команда); вставьте); addbutton ("5", 1, 3, 1, addbutton ("6", 2, 3, 1, 1, вставка); addbutton ("*", 3, 3, 1, 1, команда); addbutton ("1", 0, 4, 1, 1, вставка); addbutton ("2", 1, 1, 1, 1, ins. 1, вставка); addbutton ("-", 3, 4, 1, 1, команда); addbutton ("0", 0, 5, 1, 1, вставка); // addbutton ("+/-", 1, 5, 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 (строка метка, int row, int column, int with, int height, actionLister alluster) {jbutton button = new jbutton (label); constraints.gridx = row; с; ограничения. gridHeight = height; ruptaints.fill = gridbagConstraints.both; button.addactionListener (слушатель); layout.setConstraints (кнопка, ограничения); контейнер. {displayfield.settext (""); start = false; if (input.equals ("+/-")) displayfield.settext (displayfield.getText ()+"-");} if (! input.equals ("+/-")) {if (input.equals ("backspace")) {string strulfield.getfield (); Displayfield.settext (str.substring (0, str.length () - 1));} else if (input.equals ("ce") || input.equals ("c")) {displayfield.settext ("0"); start = true;} elsedisplayfield.settext (displayfield.gettext (") + input); ActionPerformed (actionEvent evt) {string command = evt.getActionCommand (); if (start) {lastCommand = command; } else {coundature (double.parsedouble (displayfield.getText ())); LastCommand = Command; start = true; } / x; displayfield.settext ("" + result);} public static void main (string [] args) {calculator canculate = new Calculator (); calculator.setDefaultCloseoperation (jframe.exit_on_close);}}Метод 2:
Импорт java.awt.*; импортировать java.awt.event.*; Private Textfield TF = New Textfield (30); частный длинный результат; Частный логический приложение = false; Частный char operator = '='; Приватная кнопка [] btn = новая кнопка [15]; public mycalculator () {initComponent (); } private void initComponent () {f = new Frame ("My Calculator v1.0"); f.setlayout (new Borderlayout ()); // кадр использует Borderlayout f.addwindowlistener (new windowdapter () {public void windowclose (windowevent evt) {System.exit (0);}}); Panel CenterPanel = New Panel (); 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 = New Panel (); tf.setEdable (false); NorthPanel.Add (TF); F.Add (NorthPanel, Borderlayout.north); } public void go () {f.pack (); f.setvisible (true); } public static void main (string [] args) {new MyCalCulator (). Go (); } /***Используйте метод внутреннего класса для реализации интерфейса прослушивателя, чтобы облегчить доступ к внутренним членам основного класса в классе. *Этот класс несет ответственность за прослушивание и обработку событий действий кнопки номера*/ class numberlistener реализует ActionListener {public void actionPerformed (actionEvent e) {if (! Приложение) {tf.settext (""); append = true; } String s = tf.getText (); s+= e.getActionCommand (); tf.settext (s); if (! btn [10] .isenabled ()) {for (int i = 10; i <= 14; i ++) btn [i] .setEnabled (true); }}} / *** Внутренний класс члена, ответственный за обработку событий кнопок оператора* / class operatorListener реализует ActionListener {public void actionPerformed (actionEvent e) {if (! Приложение) return; для (int i = 10; i <= 14; i ++) btn [i] .setEnabled (false); String s = tf.getText (); long num = long.parselong (s); // Получить количество текстового поля Append = false; // Установить добавление Switch (оператор) {case '+': result+= num; break; case '-': result- = num; break; case '*': result*= num; break; case '/': {if (num == 0) result = 0; иначе результат/= num; перерыв; } case '=': result = num; break; } tf.settext (string.valueof (result)); // Установить значение результата на текстовую строку op = e.getActionCommand (); operator = op.charat (0); // установить оператор}}}Метод 3:
Пакет Wanwa; импортировать java.util.*; public class calc {public static void main (string [] args) {scanner input = new Scanner (System.in); System.out.println ("************************* Инструкции для использования: 1. Дополнение 2. Вычитание 3. Умножение 4. Division*"); System.out.println ("*/t/t/t/t/t/t*"); System.out.println (" *********************************************** i = 0; i <100; i ++) {System.out.print ("/nplease Выберите правила работы:"); int num = input.nextint (); Switch (num) {case 1: System.out.println ("/n ****** Вы выбрали добавление *******/n"); System.out.print («Пожалуйста, введите первое adder:«); int jiashu1 = input.nextint (); system.out.print («Пожалуйста, введите второй adder:» int jiashu2 = input. IS: " + jiaShu1 +" + " + jiashu1 +" = " + (jiashu1 + jiashu2)); break; case 2: system.out.println ("/n ****** Вы выбрали вычитание *******/n "); System.out.print (« Пожалуйста, введите субтрокцию: »); input.nextint (); System.out.print («Пожалуйста, введите вычитание:»); 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 + » + chaNENG. (Chengfa1*chengfa2)); Break; Case 4: System.out.println ("/n ****** Вы выбрали разделение *******/n"); System.out.print ("Пожалуйста, введите Divisor:"); Double chufa1 = input.nextint (); System.out.print ("Phtive The Divisor:"); input.nextint (); system.out.println («Результат операции:» + chufa1 + » /« + chufa2 + »=» + (chufa1 / chufa2) + "yu" + (chufa1 % chufa2); break; docke: system.ut.print переоборудовать! "); Break;}}}}Метод 4:
Пакет Wanwa; импорт java.awt.*; import java.awt.event.*; import javax.swing.*; Calculator Public Class Calculator Extends jframe {частный контейнер контейнер; частный схема Gridbaglayout; частная строка Сохранить Результат расчета Private Boolean Start; // Определить, является ли это началом численного общедоступного калькулятора () {Super ("Calculator"); Container = getContentPane (); Layout = new Gridbaglayout (); контейнер.setlayout (layout); ограничения = new Gridbonstraints (); start = ruptemant = 0; JTextField (20); DisplayField.SethorizontalAlignment (jtextfield.right); ограничения. Gridx = 0; ограничения. Gridy = 0; ограничения. GridWidth = 4; ограничения. GridHeight = 1; ограничения. 100; Layout.SetConstraints (DisplayField, ограничения); Container.Add (Displayfield); actionListener insert = new InsertAction (); actionListener Command = New CommandAction (); // addButton («BackSpace», 0, 1, 2, 1, INSERT); // AddButton («CE», 1, 1, 1, 1, INSERT); 1, вставка); addbutton ("7", 0, 2, 1, 1, вставка); addbutton ("8", 1, 2, 1, 1, вставка); addbutton ("9", 2, 2, 1, 1, вставка); Addbutton ("/", 3, 1, 1, команда); вставьте); addbutton ("5", 1, 3, 1, addbutton ("6", 2, 3, 1, 1, вставка); addbutton ("*", 3, 3, 1, 1, команда); addbutton ("1", 0, 4, 1, 1, вставка); addbutton ("2", 1, 1, 1, 1, ins. 1, вставка); addbutton ("-", 3, 4, 1, 1, команда); addbutton ("0", 0, 5, 1, 1, вставка); // addbutton ("+/-", 1, 5, 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 (строка метка, int row, int column, int with, int height, actionLister alluster) {jbutton button = new jbutton (label); constraints.gridx = row; с; ограничения. gridHeight = height; ruptaints.fill = gridbagConstraints.both; button.addactionListener (слушатель); layout.setConstraints (кнопка, ограничения); контейнер. {displayfield.settext (""); start = false; if (input.equals ("+/-")) displayfield.settext (displayfield.getText ()+"-");} if (! input.equals ("+/-")) {if (input.equals ("backspace")) {string strulfield.getfield (); Displayfield.settext (str.substring (0, str.length () - 1));} else if (input.equals ("ce") || input.equals ("c")) {displayfield.settext ("0"); start = true;} elsedisplayfield.settext (displayfield.gettext (") + input); ActionPerformed (actionEvent evt) {string command = evt.getActionCommand (); if (start) {lastCommand = command; } else {coundature (double.parsedouble (displayfield.getText ())); LastCommand = Command; start = true; } / x; displayfield.settext ("" + result);} public static void main (string [] args) {calculator canculate = new Calculator (); calculator.setDefaultCloseoperation (jframe.exit_on_close);}}Я надеюсь, что эта статья будет полезна для всех Java Programming.