Написал калькулятор, но он не работает - Java

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

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

Нужно сделать калькулятор на Java, делаю-делаю - не делается :с Пишу в Ecpipse Пишу неделю наверно, не совсем ещё разобрался. Помогите пожалуйста, заранее спасибо Вот весь код
Листинг программы
  1. package plus;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.awt.event.ActionEvent;
  5. import java.awt.event.ActionListener;
  6. public class plusFrame extends JFrame {
  7. private JTextField textField;
  8. private JTextField display;
  9. public plusFrame() {
  10. getContentPane().setLayout(null);
  11. display = new JTextField();
  12. display.setBounds(0, 11, 258, 20);
  13. getContentPane().add(display);
  14. display.setColumns(10);
  15. JPanel buttonpanel = new JPanel();
  16. buttonpanel.setBounds(0, 48, 258, 246);
  17. getContentPane().add(buttonpanel);
  18. buttonpanel.setLayout(null);
  19. JButton button0 = new JButton("0");
  20. button0.setBounds(10, 212, 89, 23);
  21. buttonpanel.add(button0);
  22. JButton button1 = new JButton("1");
  23. button1.setBounds(10, 178, 39, 23);
  24. buttonpanel.add(button1);
  25. JButton button2 = new JButton("2");
  26. button2.setBounds(58, 178, 39, 23);
  27. buttonpanel.add(button2);
  28. JButton button3 = new JButton("3");
  29. button3.setBounds(107, 178, 39, 23);
  30. buttonpanel.add(button3);
  31. JButton button4 = new JButton("4");
  32. button4.setBounds(10, 144, 39, 23);
  33. buttonpanel.add(button4);
  34. JButton button5 = new JButton("5");
  35. button5.setBounds(58, 144, 39, 23);
  36. buttonpanel.add(button5);
  37. JButton button6 = new JButton("6");
  38. button6.setBounds(107, 144, 39, 23);
  39. buttonpanel.add(button6);
  40. JButton button7 = new JButton("7");
  41. button7.setBounds(10, 110, 39, 23);
  42. buttonpanel.add(button7);
  43. JButton button8 = new JButton("8");
  44. button8.setBounds(58, 110, 39, 23);
  45. buttonpanel.add(button8);
  46. JButton button9 = new JButton("9");
  47. button9.setBounds(107, 110, 39, 23);
  48. buttonpanel.add(button9);
  49. JButton buttonSum = new JButton("+");
  50. buttonSum.setBounds(149, 212, 41, 23);
  51. buttonpanel.add(buttonSum);
  52. JButton buttonBack = new JButton("C");
  53. buttonBack.setBounds(107, 77, 39, 23);
  54. buttonpanel.add(buttonBack);
  55. JButton buttonDivide = new JButton("/");
  56. buttonDivide.setBounds(149, 110, 41, 23);
  57. buttonpanel.add(buttonDivide);
  58. JButton buttonSub = new JButton("-");
  59. buttonSub.setBounds(149, 178, 41, 23);
  60. buttonpanel.add(buttonSub);
  61. JButton buttonMul = new JButton("*");
  62. buttonMul.setBounds(149, 144, 41, 23);
  63. buttonpanel.add(buttonMul);
  64. JButton buttonStart = new JButton("=");
  65. buttonStart.setBounds(193, 178, 55, 57);
  66. buttonpanel.add(buttonStart);
  67. //
  68. int firstValue = 0;
  69. String operation = "+";
  70. button0.addActionListener(new ActionListener() {
  71. @Override
  72. public void actionPerformed(ActionEvent e) {
  73. display.setText(display.getText()+"0");
  74. }
  75. });
  76. button1.addActionListener(new ActionListener() {
  77. @Override
  78. public void actionPerformed(ActionEvent e) {
  79. display.setText(display.getText()+"1");
  80. }
  81. });
  82. button2.addActionListener(new ActionListener() {
  83. @Override
  84. public void actionPerformed(ActionEvent e) {
  85. display.setText(display.getText()+"2");
  86. }
  87. });
  88. button3.addActionListener(new ActionListener() {
  89. @Override
  90. public void actionPerformed(ActionEvent e) {
  91. display.setText(display.getText()+"3");
  92. }
  93. });
  94. button4.addActionListener(new ActionListener() {
  95. @Override
  96. public void actionPerformed(ActionEvent e) {
  97. display.setText(display.getText()+"4");
  98. }
  99. });
  100. button5.addActionListener(new ActionListener() {
  101. @Override
  102. public void actionPerformed(ActionEvent e) {
  103. display.setText(display.getText()+"5");
  104. }
  105. });
  106. button6.addActionListener(new ActionListener() {
  107. @Override
  108. public void actionPerformed(ActionEvent e) {
  109. display.setText(display.getText()+"6");
  110. }
  111. });
  112. button7.addActionListener(new ActionListener() {
  113. @Override
  114. public void actionPerformed(ActionEvent e) {
  115. display.setText(display.getText()+"7");
  116. }
  117. });
  118. button8.addActionListener(new ActionListener() {
  119. @Override
  120. public void actionPerformed(ActionEvent e) {
  121. display.setText(display.getText()+"8");
  122. }
  123. });
  124. button9.addActionListener(new ActionListener() {
  125. @Override
  126. public void actionPerformed(ActionEvent e) {
  127. display.setText(display.getText()+"9");
  128. }
  129. });
  130. buttonBack.addActionListener(new ActionListener() {
  131. @Override
  132. public void actionPerformed(ActionEvent e) {
  133. String temp = display.getText();
  134. display.setText(temp.substring(0,temp.length()-1));
  135. }
  136. });
  137. buttonSum.addActionListener(new ActionListener() {
  138. @Override
  139. public void actionPerformed(ActionEvent e) {
  140. firstValue = Integer.valueOf(display.getText());
  141. display.setText("");
  142. operation = "+";
  143. }
  144. });
  145. buttonMul.addActionListener(new ActionListener() {
  146. @Override
  147. public void actionPerformed(ActionEvent e) {
  148. firstValue = Integer.valueOf(display.getText());
  149. display.setText("");
  150. operation = "*";
  151. }
  152. });
  153. buttonDivide.addActionListener(new ActionListener() {
  154. @Override
  155. public void actionPerformed(ActionEvent e) {
  156. firstValue = Integer.valueOf(display.getText());
  157. display.setText("");
  158. operation = "/";
  159. }
  160. });
  161. buttonSub.addActionListener(new ActionListener() {
  162. @Override
  163. public void actionPerformed(ActionEvent e) {
  164. firstValue = Integer.valueOf(display.getText());
  165. display.setText("");
  166. operation = "-";
  167. }
  168. });
  169. buttonStart.addActionListener(new ActionListener() {
  170. @Override
  171. public void actionPerformed(ActionEvent e) {
  172. int secondValue = Integer.valueOf(display.getText());
  173. if("+".equals(operation)){
  174. display.setText((firstValue+secondValue)+"");
  175. }
  176. if("-".equals(operation)){
  177. display.setText((firstValue-secondValue)+"");
  178. }
  179. if("*".equals(operation)){
  180. display.setText((firstValue*secondValue)+"");
  181. }
  182. if("/".equals(operation)){
  183. display.setText((firstValue/secondValue)+"");
  184. }
  185. firstValue = 0;
  186. operation = "+";
  187. }
  188. });
  189. //
  190. }
  191. public static void main(String[] args) {
  192. new plusFrame();
  193. }
  194. }
1 скрин - ошибка 2 скрин вкладки Design

Решение задачи: «Написал калькулятор, но он не работает»

textual
Листинг программы
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5.  
  6.  
  7. class CalcFrame extends JFrame {
  8.  
  9.     CalcController controller;
  10.  
  11.     private TextField display;
  12.  
  13.     public CalcFrame() throws HeadlessException {
  14.         setContentPane(constructContent());
  15.         pack();
  16.     }
  17.  
  18.     private Container constructContent() {
  19.         this.setTitle("Calc");
  20.         this.display = new TextField(20);
  21.  
  22.         JPanel root = new JPanel();
  23.         JPanel buttonsPanel = new JPanel();
  24.         JPanel digitPanel = new JPanel(new GridLayout(4, 3));
  25.         JPanel operationPanel = new JPanel(new GridLayout(4, 1));
  26.  
  27.         String[] buttonNames = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "C", "="};
  28.  
  29.         for (String  s : buttonNames) {
  30.             digitPanel.add(createButton(s));
  31.         }
  32.  
  33.         String[] operations = {"+", "-", "*", "/"};
  34.  
  35.         for (String s : operations) {
  36.             operationPanel.add(createButton(s));
  37.         }
  38.  
  39.         buttonsPanel.setLayout((new BoxLayout(buttonsPanel, BoxLayout.X_AXIS)));
  40.         buttonsPanel.add(digitPanel);
  41.         buttonsPanel.add(operationPanel);
  42.  
  43.         root.setLayout((new BoxLayout(root, BoxLayout.Y_AXIS)));
  44.         root.add(this.display);
  45.         root.add(buttonsPanel);
  46.  
  47.         return root;
  48.     }
  49.  
  50.     private Component createButton(final String s) {
  51.         Button button = new Button(s);
  52.         button.addActionListener(new ActionListener() {
  53.             @Override
  54.             public void actionPerformed(ActionEvent e) {
  55.                 controller.pushButton(s);
  56.             }
  57.         });
  58.         return button;
  59.     }
  60.  
  61.     public void setController(CalcController controller) {
  62.         this.controller = controller;
  63.     }
  64.  
  65.     public void update(String data) {
  66.         display.setText(data);
  67.     }
  68.  
  69.     public void start() {
  70.         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  71.         setVisible(true);
  72.     }
  73. }
  74.  
  75.  
  76. class CalcController {
  77.  
  78.     CalcData data;
  79.  
  80.     public void setData(CalcData data) {
  81.         this.data = data;
  82.     }
  83.  
  84.     public void pushButton(String buttonValue) {
  85.  
  86.         if (hasError(data.getData(), buttonValue)) {
  87.             return;
  88.         }
  89.  
  90.         if (buttonValue.equals("=")) {
  91.             String result = calculateExpression(data.getData());
  92.             data.setData(result);
  93.             return;
  94.         }
  95.  
  96.         if (buttonValue.equals("C")) {
  97.             data.setData("");
  98.             return;
  99.         }
  100.  
  101.         StringBuilder sb = new StringBuilder();
  102.         sb.append(data.getData());
  103.         sb.append(buttonValue);
  104.         data.setData(sb.toString());
  105.     }
  106.  
  107.     private boolean hasError(String data, String buttonValue) {
  108.         //тут добавить проверку что бы нельзя было ввести 2 символа операций подряд
  109.         //например 2+-2
  110.         return false;
  111.     }
  112.  
  113.     private String calculateExpression(String data) {
  114.         //Тут (или вынести в отдельный класс) логика вычисления выражения
  115.         //Гуглить - "Обратная польская нотация"
  116.         return "метод не реализован";
  117.     }
  118.  
  119.  
  120. }
  121.  
  122.  
  123. class CalcData {
  124.  
  125.     CalcFrame view;
  126.     String data = new String();
  127.  
  128.     public void setView(CalcFrame view) {
  129.         this.view = view;
  130.     }
  131.  
  132.     public String getData() {
  133.         return data;
  134.     }
  135.  
  136.     public void setData(String data) {
  137.         this.data = data;
  138.         notifyView();
  139.     }
  140.  
  141.     private void notifyView() {
  142.         view.update(getData());
  143.     }
  144. }
  145.  
  146.  
  147. public class Calculator {
  148.  
  149.     public static void main(String[] args) {
  150.         CalcFrame frame = new CalcFrame();
  151.         CalcController controller = new CalcController();
  152.         CalcData data = new CalcData();
  153.  
  154.         frame.setController(controller);
  155.         controller.setData(data);
  156.         data.setView(frame);
  157.  
  158.         frame.start();
  159.     }
  160. }

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


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

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

15   голосов , оценка 4.2 из 5

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

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

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