Калькулятор - Java (241453)

Узнай цену своей работы

Формулировка задачи:

Помогите разобраться, почему после нажатия кнопки "=" не вычисляется результат выражения? Код выполняющий вычисление результата как то некорректно выполняет свою роботу, а почему не могу понять
Листинг программы
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. /**
  5. * Created by blizardinka on 02.11.15.
  6. */
  7. public class Calculator {
  8. public static void main(String[] args) {
  9. EventQueue.invokeLater(new Runnable() {
  10. public void run() {
  11. CalculatorFrame frame = new CalculatorFrame();
  12. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  13. frame.setVisible(true);
  14. }
  15. });
  16. }
  17. }
  18. /**
  19. * Фрейм с панелью калькулятора()
  20. */
  21. class CalculatorFrame extends JFrame {
  22. public CalculatorFrame() {
  23. setTitle("Calculator");
  24. CalculatorPanel panel = new CalculatorPanel();
  25. add(panel);
  26. pack();
  27. }
  28. }
  29. /**
  30. * Панель с кнопками калькулятора и элементом
  31. * для отображение результатов вычислений
  32. */
  33. class CalculatorPanel extends JPanel {
  34. public CalculatorPanel() {
  35. setLayout(new BorderLayout());
  36. result = 0;
  37. lastCommand = "=";
  38. start = true;
  39. //Добавление элемента для отображения результата
  40. display = new JButton("0");
  41. display.setEnabled(false);
  42. add(display, BorderLayout.NORTH);
  43. ActionListener insert = new InsertAction();
  44. ActionListener command = new CommandAction();
  45. //Размещение кнопок в виде сетки 4х4
  46. panel = new JPanel();
  47. panel.setLayout(new GridLayout(4, 4));
  48. addButton("7", insert);
  49. addButton("8", insert);
  50. addButton("9", insert);
  51. addButton("/", command);
  52. addButton("4", insert);
  53. addButton("5", insert);
  54. addButton("6", insert);
  55. addButton("*", command);
  56. addButton("1", insert);
  57. addButton("2", insert);
  58. addButton("3", insert);
  59. addButton("-", command);
  60. addButton("0", insert);
  61. addButton("+", insert);
  62. addButton("=", insert);
  63. addButton(".", command);
  64. add(panel, BorderLayout.CENTER);
  65. }
  66. /**
  67. *Добавление к центральной панели
  68. * @param label Надпись на кнопке
  69. * @param listener Слушатель кнопки
  70. */
  71. private void addButton(String label, ActionListener listener) {
  72. JButton button = new JButton(label);
  73. button.addActionListener(listener);
  74. panel.add(button);
  75. }
  76. /**
  77. * При обработки события строка, связаная с кнопкой,
  78. * помещается в конец отображаемого текста
  79. */
  80. private class InsertAction implements ActionListener {
  81. public void actionPerformed(ActionEvent event) {
  82. String input = event.getActionCommand();
  83. if (start) {
  84. display.setText("");
  85. start = false;
  86. }
  87. display.setText(display.getText() + input);
  88. }
  89. }
  90. /**
  91. * При обработке события выполняется команда, которая
  92. * определяется строкой, связанной с кнопкой
  93. */
  94. private class CommandAction implements ActionListener {
  95. public void actionPerformed(ActionEvent event) {
  96. String command = event.getActionCommand();
  97. if (start) {
  98. if (command.equals("-")) {
  99. display.setText(command);
  100. start = false;
  101. }
  102. else lastCommand = command;
  103. } else {
  104. calculate(Double.parseDouble(display.getText()));
  105. lastCommand = command;
  106. start = true;
  107. }
  108. }
  109. }
  110. /**
  111. * Выполнение вычислений
  112. * @param x Значение, накапливающее предыдущие результаты
  113. */
  114. public void calculate(double x) {
  115. if (lastCommand.equals("+")) result += x;
  116. else if (lastCommand.equals("-")) result -= x;
  117. else if (lastCommand.equals("*")) result *= x;
  118. else if (lastCommand.equals("/")) result /= x;
  119. else if (lastCommand.equals("=")) result = x;
  120. display.setText("" + result);
  121. }
  122. private JButton display;
  123. private JPanel panel;
  124. private double result;
  125. private String lastCommand;
  126. private boolean start;
  127. }

Решение задачи: «Калькулятор»

textual
Листинг программы
  1. public CalculatorPanel() {
  2.         setLayout(new BorderLayout());
  3.  
  4.         result = 0;
  5.         lastCommand = "=";
  6.         start = true;
  7.  
  8.         //Добавление элемента для отображения результата
  9.  
  10.         display = new JButton("0");
  11.         display.setEnabled(false);
  12.         add(display, BorderLayout.NORTH);
  13.  
  14.         ActionListener insert = new InsertAction();
  15.         ActionListener command = new CommandAction();
  16.  
  17.         //Размещение кнопок в виде сетки 4х4
  18.  
  19.         panel = new JPanel();
  20.         panel.setLayout(new GridLayout(4, 5));
  21.  
  22.         addButton("7", insert);
  23.         addButton("8", insert);
  24.         addButton("9", insert);
  25.         addButton("/", command);
  26.  
  27.         addButton("4", insert);
  28.         addButton("5", insert);
  29.         addButton("6", insert);
  30.         addButton("*", command);
  31.  
  32.         addButton("1", insert);
  33.         addButton("2", insert);
  34.         addButton("3", insert);
  35.         addButton("-", command);
  36.  
  37.         addButton("0", insert);
  38.         addButton(".", insert);
  39.         addButton("=", command);
  40.         addButton("+", command);
  41.  
  42.         add(panel, BorderLayout.CENTER);
  43.         JButton buttonBack = new JButton("C");//кнопка С
  44.         panel.add(buttonBack);
  45.         buttonBack.addActionListener(new ActionListener() {
  46.             @Override
  47.             public void actionPerformed(ActionEvent e) {
  48.                 String temp = display.getText();
  49.                 display.setText(temp.substring(0,temp.length()-1));
  50.             }
  51.         });
  52.     }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

12   голосов , оценка 3.833 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут