在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Java编写计算器的常见方法实例总结

2016-7-29 15:41| 发布者: zhangjf| 查看: 486| 评论: 0

摘要: 本文实例总结了Java编写计算器的常见方法。分享给大家供大家参考,具体如下: 方法一: package wanwa;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Calculator extends JFrame {p ...

本文实例总结了Java编写计算器的常见方法。分享给大家供大家参考,具体如下:

方法一:

  1. package wanwa;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import javax.swing.*;
  5. public class Calculator extends JFrame {
  6. private Container container;
  7. private GridBagLayout layout;
  8. private GridBagConstraints constraints;
  9. private JTextField displayField;// 计算结果显示区
  10. private String lastCommand;// 保存+,-,*,/,=命令
  11. private double result;// 保存计算结果
  12. private boolean start;// 判断是否为数字的开始
  13. public Calculator() {
  14. super("Calculator");
  15. container = getContentPane();
  16. layout = new GridBagLayout();
  17. container.setLayout(layout);
  18. constraints = new GridBagConstraints();
  19. start = true;
  20. result = 0;
  21. lastCommand = "=";
  22. displayField = new JTextField(20);
  23. displayField.setHorizontalAlignment(JTextField.RIGHT);
  24. constraints.gridx = 0;
  25. constraints.gridy = 0;
  26. constraints.gridwidth = 4;
  27. constraints.gridheight = 1;
  28. constraints.fill = GridBagConstraints.BOTH;
  29. constraints.weightx = 100;
  30. constraints.weighty = 100;
  31. layout.setConstraints(displayField, constraints);
  32. container.add(displayField);
  33. ActionListener insert = new InsertAction();
  34. ActionListener command = new CommandAction();
  35. // addButton("Backspace", 0, 1, 2, 1, insert);
  36. // addButton("CE", 2, 1, 1, 1, insert);
  37. // addButton("C", 3, 1, 1, 1, insert);
  38. addButton("7", 0, 2, 1, 1, insert);
  39. addButton("8", 1, 2, 1, 1, insert);
  40. addButton("9", 2, 2, 1, 1, insert);
  41. addButton("/", 3, 2, 1, 1, command);
  42. addButton("4", 0, 3, 1, 1, insert);
  43. addButton("5", 1, 3, 1, 1, insert);
  44. addButton("6", 2, 3, 1, 1, insert);
  45. addButton("*", 3, 3, 1, 1, command);
  46. addButton("1", 0, 4, 1, 1, insert);
  47. addButton("2", 1, 4, 1, 1, insert);
  48. addButton("3", 2, 4, 1, 1, insert);
  49. addButton("-", 3, 4, 1, 1, command);
  50. addButton("0", 0, 5, 1, 1, insert);
  51. // addButton("+/-", 1, 5, 1, 1, insert);// 只显示"-"号,"+"没有实用价值
  52. addButton(".", 2, 5, 1, 1, insert);
  53. addButton("+", 3, 5, 1, 1, command);
  54. addButton("=", 0, 6, 4, 1, command);
  55. this.setResizable(false);
  56. setSize(180, 200);
  57. setVisible(true);
  58. }
  59. private void addButton(String label, int row, int column, int with,
  60. int height, ActionListener listener) {
  61. JButton button = new JButton(label);
  62. constraints.gridx = row;
  63. constraints.gridy = column;
  64. constraints.gridwidth = with;
  65. constraints.gridheight = height;
  66. constraints.fill = GridBagConstraints.BOTH;
  67. button.addActionListener(listener);
  68. layout.setConstraints(button, constraints);
  69. container.add(button);
  70. }
  71. private class InsertAction implements ActionListener {
  72. public void actionPerformed(ActionEvent event) {
  73. String input = event.getActionCommand();
  74. if (start) {
  75. displayField.setText("");
  76. start = false;
  77. if (input.equals("+/-"))
  78. displayField.setText(displayField.getText() + "-");
  79. }
  80. if (!input.equals("+/-")) {
  81. if (input.equals("Backspace")) {
  82. String str = displayField.getText();
  83. if (str.length() > 0)
  84. displayField.setText(str.substring(0, str.length() - 1));
  85. } else if (input.equals("CE") || input.equals("C")) {
  86. displayField.setText("0");
  87. start = true;
  88. } else
  89. displayField.setText(displayField.getText() + input);
  90. }
  91. }
  92. }
  93. private class CommandAction implements ActionListener {
  94. public void actionPerformed(ActionEvent evt) {
  95. String command = evt.getActionCommand();
  96. if (start) {
  97. lastCommand = command;
  98. } else {
  99. calculate(Double.parseDouble(displayField.getText()));
  100. lastCommand = command;
  101. start = true;
  102. }
  103. }
  104. }
  105. public void calculate(double x) {
  106. if (lastCommand.equals("+"))
  107. result += x;
  108. else if (lastCommand.equals("-"))
  109. result -= x;
  110. else if (lastCommand.equals("*"))
  111. result *= x;
  112. else if (lastCommand.equals("/"))
  113. result /= x;
  114. else if (lastCommand.equals("="))
  115. result = x;
  116. displayField.setText("" + result);
  117. }
  118. public static void main(String[] args) {
  119. Calculator calculator = new Calculator();
  120. calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  121. }
  122. }
复制代码

方法二:

  1. import java.awt.*;
  2. import java.awt.event.*;
  3. public class MyCalculator {
  4. PRivate Frame f;
  5. private TextField tf = new TextField(30);
  6. private long result;
  7. private boolean append=false;
  8. private char Operator='=';
  9. private Button[] btn=new Button[15];
  10. public MyCalculator() {
  11. initComponent();
  12. }
  13. private void initComponent() {
  14. f = new Frame("My Calculator V1.0");
  15. f.setLayout(new BorderLayout()); //The frame uses BorderLayout
  16. f.addWindowListener(new WindowAdapter() {
  17. public void windowClosing(WindowEvent evt) {
  18. System.exit(0);
  19. }
  20. });
  21. Panel centerPanel = new Panel();
  22. centerPanel.setLayout(new GridLayout(5, 3)); //The panel uses GridLayout
  23. NumberListener nl=new NumberListener();
  24. OperatorListener ol=new OperatorListener();
  25. btn[10]=new Button("+");
  26. btn[11]=new Button("-");
  27. btn[12]=new Button("*");
  28. btn[13]=new Button("/");
  29. btn[14]=new Button("=");
  30. for (int i=0;i<=9;i++){
  31. btn[i]=new Button(String.valueOf(i));
  32. centerPanel.add(btn[i]);
  33. btn[i].addActionListener(nl);
  34. if (i%2==1){
  35. centerPanel.add(btn[(i+19)/2]);
  36. btn[(i+19)/2].addActionListener(ol);
  37. }
  38. }
  39. f.add(centerPanel, BorderLayout.CENTER);
  40. Panel northPanel = new Panel();
  41. tf.setEditable(false);
  42. northPanel.add(tf);
  43. f.add(northPanel, BorderLayout.NORTH);
  44. }
  45. public void go() {
  46. f.pack();
  47. f.setVisible(true);
  48. }
  49. public static void main(String[] args) {
  50. new MyCalculator().go();
  51. }
  52. /**
  53. *采用成员内部类方式,实现监听器接口,方便访问主类内类内部成员。
  54. *此类负责数字按钮Action事件监听和处理
  55. */
  56. class NumberListener implements ActionListener{
  57. public void actionPerformed(ActionEvent e){
  58. if (!append) {
  59. tf.setText("");
  60. append=true;
  61. }
  62. String s=tf.getText();
  63. s+=e.getActionCommand();
  64. tf.setText(s);
  65. if (!btn[10].isEnabled()){
  66. for(int i=10;i<=14;i++) btn[i].setEnabled(true);
  67. }
  68. }
  69. }
  70. /**
  71. * 成员内部类,负责操作符按钮的事件处理
  72. */
  73. class OperatorListener implements ActionListener{
  74. public void actionPerformed(ActionEvent e){
  75. if (!append) return;
  76. for(int i=10;i<=14;i++) btn[i].setEnabled(false);
  77. String s=tf.getText();
  78. long num=Long.parseLong(s);//get the number of textfield
  79. append=false; //set append
  80. switch(operator){
  81. case '+':result+=num;break;
  82. case '-':result-=num;break;
  83. case '*':result*=num;break;
  84. case '/':{
  85. if (num==0) result=0;
  86. else result/=num;
  87. break;
  88. }
  89. case '=':result=num;break;
  90. }
  91. tf.setText(String.valueOf(result));
  92. //set the value of result to textfield
  93. String op=e.getActionCommand();
  94. operator=op.charAt(0); // set operator
  95. }
  96. }
  97. }
复制代码

方法三:

  1. package wanwa;
  2. import java.util.*;
  3. public class calc {
  4. public static void main(String[] args) {
  5. Scanner input = new Scanner(System.in);
  6. System.out.println("*****************简易计算器****************");
  7. System.out.println("*ttttt*");
  8. System.out.println("* 使用说明: 1.加法 2.减法 3.乘法 4.除法 *");
  9. System.out.println("*ttttt*");
  10. System.out.println("*****************************************");
  11. for(int i=0;i<100;i++){
  12. System.out.print("n请选择运算规则:");
  13. int num = input.nextInt();
  14. switch(num){
  15. case 1:
  16. System.out.println("n******你选择了加法******n");
  17. System.out.print("请输入第1个加数:");
  18. int jiashu1 = input.nextInt();
  19. System.out.print("请输入第2个加数:");
  20. int jiashu2 = input.nextInt();
  21. System.out.println("运算结果为:" + jiashu1 + " + " + jiashu1 + " = " + (jiashu1 + jiashu2));
  22. break;
  23. case 2:
  24. System.out.println("n******你选择了减法******n");
  25. System.out.print("请输入被减数:");
  26. int jianshu1 = input.nextInt();
  27. System.out.print("请输入减数:");
  28. int jianshu2 = input.nextInt();
  29. System.out.println("运算结果为:" + jianshu1 + " - " + jianshu2 + " = " + (jianshu1 - jianshu2));
  30. break;
  31. case 3:
  32. System.out.println("n******你选择了乘法******n");
  33. System.out.print("请输入第1个因数:");
  34. int chengfa1 = input.nextInt();
  35. System.out.print("请输入第2个因数:");
  36. int chengfa2 = input.nextInt();
  37. System.out.println("运算结果为:" + chengfa1 + " * " + chengfa2 + " = " + (chengfa1 * chengfa2));
  38. break;
  39. case 4:
  40. System.out.println("n******你选择了除法******n");
  41. System.out.print("请输入被除数:");
  42. double chufa1 = input.nextInt();
  43. System.out.print("请输入除数:");
  44. double chufa2 = input.nextInt();
  45. System.out.println("运算结果为:" + chufa1 + " / " + chufa2 + " = " + (chufa1 / chufa2) + " 余 " + (chufa1 % chufa2));
  46. break;
  47. default:
  48. System.out.println("n你的选择有错,请重新选择!");
  49. break;
  50. }
  51. }
  52. }
  53. }
复制代码

方法四:

  1. package wanwa;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import javax.swing.*;
  5. public class Calculator extends JFrame {
  6. private Container container;
  7. private GridBagLayout layout;
  8. private GridBagConstraints constraints;
  9. private JTextField displayField;// 计算结果显示区
  10. private String lastCommand;// 保存+,-,*,/,=命令
  11. private double result;// 保存计算结果
  12. private boolean start;// 判断是否为数字的开始
  13. public Calculator() {
  14. super("Calculator");
  15. container = getContentPane();
  16. layout = new GridBagLayout();
  17. container.setLayout(layout);
  18. constraints = new GridBagConstraints();
  19. start = true;
  20. result = 0;
  21. lastCommand = "=";
  22. displayField = new JTextField(20);
  23. displayField.setHorizontalAlignment(JTextField.RIGHT);
  24. constraints.gridx = 0;
  25. constraints.gridy = 0;
  26. constraints.gridwidth = 4;
  27. constraints.gridheight = 1;
  28. constraints.fill = GridBagConstraints.BOTH;
  29. constraints.weightx = 100;
  30. constraints.weighty = 100;
  31. layout.setConstraints(displayField, constraints);
  32. container.add(displayField);
  33. ActionListener insert = new InsertAction();
  34. ActionListener command = new CommandAction();
  35. // addButton("Backspace", 0, 1, 2, 1, insert);
  36. // addButton("CE", 2, 1, 1, 1, insert);
  37. // addButton("C", 3, 1, 1, 1, insert);
  38. addButton("7", 0, 2, 1, 1, insert);
  39. addButton("8", 1, 2, 1, 1, insert);
  40. addButton("9", 2, 2, 1, 1, insert);
  41. addButton("/", 3, 2, 1, 1, command);
  42. addButton("4", 0, 3, 1, 1, insert);
  43. addButton("5", 1, 3, 1, 1, insert);
  44. addButton("6", 2, 3, 1, 1, insert);
  45. addButton("*", 3, 3, 1, 1, command);
  46. addButton("1", 0, 4, 1, 1, insert);
  47. addButton("2", 1, 4, 1, 1, insert);
  48. addButton("3", 2, 4, 1, 1, insert);
  49. addButton("-", 3, 4, 1, 1, command);
  50. addButton("0", 0, 5, 1, 1, insert);
  51. // addButton("+/-", 1, 5, 1, 1, insert);// 只显示"-"号,"+"没有实用价值
  52. addButton(".", 2, 5, 1, 1, insert);
  53. addButton("+", 3, 5, 1, 1, command);
  54. addButton("=", 0, 6, 4, 1, command);
  55. this.setResizable(false);
  56. setSize(180, 200);
  57. setVisible(true);
  58. }
  59. private void addButton(String label, int row, int column, int with,
  60. int height, ActionListener listener) {
  61. JButton button = new JButton(label);
  62. constraints.gridx = row;
  63. constraints.gridy = column;
  64. constraints.gridwidth = with;
  65. constraints.gridheight = height;
  66. constraints.fill = GridBagConstraints.BOTH;
  67. button.addActionListener(listener);
  68. layout.setConstraints(button, constraints);
  69. container.add(button);
  70. }
  71. private class InsertAction implements ActionListener {
  72. public void actionPerformed(ActionEvent event) {
  73. String input = event.getActionCommand();
  74. if (start) {
  75. displayField.setText("");
  76. start = false;
  77. if (input.equals("+/-"))
  78. displayField.setText(displayField.getText() + "-");
  79. }
  80. if (!input.equals("+/-")) {
  81. if (input.equals("Backspace")) {
  82. String str = displayField.getText();
  83. if (str.length() > 0)
  84. displayField.setText(str.substring(0, str.length() - 1));
  85. } else if (input.equals("CE") || input.equals("C")) {
  86. displayField.setText("0");
  87. start = true;
  88. } else
  89. displayField.setText(displayField.getText() + input);
  90. }
  91. }
  92. }
  93. private class CommandAction implements ActionListener {
  94. public void actionPerformed(ActionEvent evt) {
  95. String command = evt.getActionCommand();
  96. if (start) {
  97. lastCommand = command;
  98. } else {
  99. calculate(Double.parseDouble(displayField.getText()));
  100. lastCommand = command;
  101. start = true;
  102. }
  103. }
  104. }
  105. public void calculate(double x) {
  106. if (lastCommand.equals("+"))
  107. result += x;
  108. else if (lastCommand.equals("-"))
  109. result -= x;
  110. else if (lastCommand.equals("*"))
  111. result *= x;
  112. else if (lastCommand.equals("/"))
  113. result /= x;
  114. else if (lastCommand.equals("="))
  115. result = x;
  116. displayField.setText("" + result);
  117. }
  118. public static void main(String[] args) {
  119. Calculator calculator = new Calculator();
  120. calculator.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
  121. }
  122. }
复制代码

希望本文所述对大家java程序设计有所帮助。

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-6 09:07

Copyright 2015-2025 djqfx

返回顶部