Este artigo resume os métodos comuns para escrever calculadoras em Java. Compartilhe -o para sua referência, como segue:
Método 1:
pacote wanwa; importar java.awt.*; importar java.awt.event.*; importar javax.swing.*; calculadora de classe pública estende jframe {contêiner privado; savor de gridbaglayout privado; Resultado; // Salvar o resultado do cálculo privado Iniciar booleano; // Determine se é o início de um número de calculador público () {super ("calculadora"); container = getContentPane (); layout = new GridBagLayout (); start.SetLayout (Layout) = novo = novo GridBagCantenS (); True; JTextfield (20); DisplayField.SethorizontalAlignment (JTextfield.right); restrições.GridX = 0; restrições.Gridy = 0; restrições. restrições); container.add (DisplayField); ActionListener insert = new InsertAction (); ActionListener Command = new CommandAction (); // addButton ("backspace", 0, 1, 2, 1, 1, insert); // addButton ("ce", 2, 1, 1, 1, 1, 1, 1, 1, 1); insert); addButton ("7", 0, 2, 1, 1, insert); addButton ("8", 1, 2, 1, 1, insert); addButton ("9", 2, 2, 1, 1, addbutton); addButton ("/", 3, 1, 1, 1, 1, comando); addbutton; 1, 3, 1, addButton("6", 2, 3, 1, 1, insert);addButton("*", 3, 3, 1, 1, command);addButton("1", 0, 4, 1, 1, insert);addButton("2", 1, 4, 1, 1, insert);addButton("3", 2, 4, 1, 1, inserir); addButton ("-", 3, 4, 1, 1, comando); addButton ("0", 0, 5, 1, 1, inserir); // addButton ("+/-", 1, 5, 1, 1, 1, 1, 1, inserção); // apenas o signo "-", ""+"" não possui um valor prático, 1, 1, inserção); inserir); addButton ("+", 3, 5, 1, 1, comando); addButton ("=", 0, 6, 4, 1, comando); this.setResizable (false); Setsize (180, 200); setVisible (true);} AddButton privado de vazio (etiqueta de string, int linha, int colun, int, int alting, ActionListener ouvinte) {jbutton Button = new JButton (LABEL); Rectraints.GridX = Row; altura; restrições. = false;if (input.equals("+/-"))displayField.setText(displayField.getText() + "-");}if (!input.equals("+/-")) { if (input.equals("Backspace")) { String str = displayField.getText();if (str.length() > 0) 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);}}}} String command = evt.getActionCommand (); if (start) {lastCommand = command; } else {calcular (duplo.parseDouble (displayfield.getText ())); lastCommand = comando; start = true; }}} public void calcular (duplo x) {if (lastCommand.equals (" +")) resultado += x; else if (lastCommand.equals (" -")) resultado -= x; else if (lastCommand.equals (" *) resultando *= x; if (lastComMAnd.And.Equals (" /Equals) (" *) resultando *= x; x; displayfield.settext ("" + resultado);} public static void main (string [] args) {calculadora calculate = new calculator (); calculator.setDefaultCloseOperation (jframe.exit_on_close);}}Método 2:
importar java.awt.*; importar java.awt.event.*; public class MyCalculator {private Frame F; Private TextField TF = novo campo de texto (30); resultado longo privado; Apêndio booleano privado = false; operador de char privado = '='; botão privado [] btn = novo botão [15]; public myCalCulator () {initComponent (); } private void initComponent () {f = new Frame ("minha calculadora v1.0"); f.SetLayout (new BorderLayout ()); // O quadro usa borderlayout f.addwindowlistener (new windowAdapter () {public void WindowClosing (WindowEvent EVT) {System.exit (0);}}); Painel centralPanel = novo painel (); CenterPanel.setLayout (New GridLayout (5, 3)); // O painel usa gridlayout numberListener nl = new NumberListener (); OperatorListener OL = new OperatorListener (); btn [10] = novo botão ("+"); btn [11] = novo botão ("-"); btn [12] = novo botão ("*"); btn [13] = novo botão ("/"); btn [14] = novo botão ("="); for (int i = 0; i <= 9; i ++) {btn [i] = novo botão (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); Painel northpanel = novo painel (); tf.seteditable (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 (); } /***Use o método de classe interna para implementar a interface do ouvinte para facilitar o acesso a membros internos da classe principal da classe. *Esta classe é responsável pela escuta e manuseio de eventos de ação do botão Número*/ classe NumberListener implementa ActionListener {public void ActionPerformed (ActionEvent E) {if (! Append) {tf.settext (""); append = true; } String s = tf.getText (); s+= e.getActionCommand (); tf.settext (s); if (! btn [10] .Imenabled ()) {for (int i = 10; i <= 14; i ++) btn [i] .setEnabled (true); }}} / *** Classe interna do membro, responsável pelo manuseio de eventos dos botões do operador* / class OperatorListener implementa ActionListener {public void actionPormed (ActionEvent e) {if (! Append) return; for (int i = 10; i <= 14; i ++) btn [i] .setEnabled (false); String s = tf.getText (); long num = long.parselong (s); // obtenha o número de textfield append = false; // defina o switch de append (operador) {case '+': resultado+= num; break; case '-': resultado- = num; quebra; case '*': resultado*= num; quebra; case '/': {if (num == 0) resultado = 0; caso contrário, resultado/= num; quebrar; } case '=': resultado = num; break; } tf.settext (string.valueof (resultado)); // Defina o valor do resultado para o texto de textfield string = e.getActionCommand (); operador = op.charat (0); // Definir operador}}}Método 3:
pacote wanwa; importar java.util.*; classe pública 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/t*"); System.out.println ("*Instruções para uso: 1. Adição 2. Subtração 3. Divisão*"); System.out.println ("*/t/t/t/t/t/t*"); System.out.println (" ********************************************************************* input.NextInt (); switch (num) {case 1: system.out.println ("/n ******** você selecionou adição *******/n"); System.out.print ("Por favor, digite o primeiro adder:"); int jiashu1 = input.NextInt (); System.out.print ("por favor. O resultado da operação é: " + jiashu1 +" + " + jiashu1 +" = " + (jiashu1 + jiashu2)); quebra; caso 2: system.out.println ("/n ****** você selecionou a subtração: " input.NextInt (); System.out.print ("Por favor, digite a subtração:"); int jianshu2 = input.NextInt (); System.out.println ("O resultado da operação é:" + jianshu1 + " -" + jiaShu2 + "=" (SIGNIMEIRO (SIGNIMEIRATHU1 - JIANSHU2); Multiplicação selecionada *********/n "); System.out.print (" Por favor, digite o primeiro fator: "); int chengfa1 = input.NextInt (); System.out.print (" Por favor, digite o segundo fator: "); int chengfa2 = input.next () system.out.println (" a operação é: "CHENC2 = CHENC2 = INPUT.NEXT (); (chengfa1*chengfa2)); quebra; caso 4: system.out.println ("/n ******** você selecionou a divisão *******/n"); system.out.print ("por favor, digite o divisor:"); por favor, por favor, diplin the DiffA1 = input.Next (); Sistema; input.NextInt (); System.out.println ("O resultado da operação é:" + chufa1 + " /" + chufa2 + "=" + (chufa1 / chufa2) + "yu" + (chufa1 % chufa2); quebra; default: system.out.println (" Re-selecionar! "); Break;}}}}Método 4:
pacote wanwa; importar java.awt.*; importar java.awt.event.*; importar javax.swing.*; calculadora de classe pública estende jframe {contêiner privado; savor de gridbaglayout privado; Resultado; // Salvar o resultado do cálculo privado Iniciar booleano; // Determine se é o início de um número de calculador público () {super ("calculadora"); container = getContentPane (); layout = new GridBagLayout (); start.SetLayout (Layout) = novo = novo GridBagCantenS (); True; JTextfield (20); DisplayField.SethorizontalAlignment (JTextfield.right); restrições.GridX = 0; restrições.Gridy = 0; restrições. restrições); container.add (DisplayField); ActionListener insert = new InsertAction (); ActionListener Command = new CommandAction (); // addButton ("backspace", 0, 1, 2, 1, 1, insert); // addButton ("ce", 2, 1, 1, 1, 1, 1, 1, 1, 1); insert); addButton ("7", 0, 2, 1, 1, insert); addButton ("8", 1, 2, 1, 1, insert); addButton ("9", 2, 2, 1, 1, addbutton); addButton ("/", 3, 1, 1, 1, 1, comando); addbutton; 1, 3, 1, addButton("6", 2, 3, 1, 1, insert);addButton("*", 3, 3, 1, 1, command);addButton("1", 0, 4, 1, 1, insert);addButton("2", 1, 4, 1, 1, insert);addButton("3", 2, 4, 1, 1, inserir); addButton ("-", 3, 4, 1, 1, comando); addButton ("0", 0, 5, 1, 1, inserir); // addButton ("+/-", 1, 5, 1, 1, 1, 1, 1, inserção); // apenas o signo "-", ""+"" não possui um valor prático, 1, 1, inserção); inserir); addButton ("+", 3, 5, 1, 1, comando); addButton ("=", 0, 6, 4, 1, comando); this.setResizable (false); Setsize (180, 200); setVisible (true);} AddButton privado de vazio (etiqueta de string, int linha, int colun, int, int alting, ActionListener ouvinte) {jbutton Button = new JButton (LABEL); Rectraints.GridX = Row; altura; restrições. = false; if (input.equals ("+/-")) DisplayField.Settext (DisplayField.getText ()+"-");} if (! input.equals ("+/-")) {if (input.equals ("backspace") {stringfieldfield.getText (); se (str.llming () () (str.lngthngth () (str.lngth () (str.lng () (str.lngth () (str.lngth () (str.lng () (str.lng () (str.lng () (str.llmen () (backspace ") {stringfield) str.Length () - 1));} else if (input.equals ("CE") || input.equals ("c")) {displayfield.settext ("0"); start = true;} elsedisplayfield.settext (displayfield.getText () + input);}}}} String command = evt.getActionCommand (); if (start) {lastCommand = command; } else {calcular (duplo.parseDouble (displayfield.getText ())); lastCommand = comando; start = true; }}} public void calcular (duplo x) {if (lastCommand.equals (" +")) resultado += x; else if (lastCommand.equals (" -")) resultado -= x; else if (lastCommand.equals (" *) resultando *= x;;; se else (lastComMCOMOMEMM) (" /Equals) resultante /; x; displayfield.settext ("" + resultado);} public static void main (string [] args) {calculadora calculate = new calculator (); calculator.setDefaultCloseOperation (jframe.exit_on_close);}}Espero que este artigo seja útil para a programação Java de todos.