StringBuilder - Java

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

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

Помогите исправить 2 ошибки. Должен быть калькулятор, который юзает файл и сохраняет калькуляцию. Ошибки выдает на методе append и getText.
Листинг программы
  1. package webstart;
  2. import java.awt.event.*;
  3. import java.beans.*;
  4. import java.io.*;
  5. import java.net.*;
  6. import javax.jnlp.*;
  7. import javax.swing.*;
  8. /**
  9. * Фрейм с панелью калькулятора и меню для загрузки и сохранения предысторий калькуляций.
  10. * Created by Михаил on 03.08.2016.
  11. */
  12. public class CalculatorFrame extends JFrame{
  13. private CalculatorPanel panel;
  14. public CalculatorFrame()
  15. {
  16. setTitle();
  17. panel = new CalculatorPanel();
  18. add(panel);
  19. JMenu fileMenu = new JMenu("File");
  20. JMenuBar menuBar = new JMenuBar();
  21. menuBar.add(fileMenu);
  22. setJMenuBar(menuBar);
  23. JMenuItem openItem = fileMenu.add("Open");
  24. openItem.addActionListener(EventHandler.create(ActionListener.class, this, "open"));
  25. JMenuItem saveItem = fileMenu.add("Save");
  26. saveItem.addActionListener(EventHandler.create(ActionListener.class, this, "save"));
  27. pack();
  28. }
  29. /**
  30. * Получает заголовок из постоянного хранилища или запрашивает
  31. * заголовок у пользователя, если он не был прежде сохранен
  32. */
  33. public void setTitle()
  34. {
  35. try
  36. {
  37. String title = null;
  38. BasicService basic =
  39. (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
  40. URL codeBase = basic.getCodeBase();
  41. PersistenceService service = (PersistenceService) ServiceManager.lookup("javax.jnlp.BasicService");
  42. URL key = new URL(codeBase, "title");
  43. try
  44. {
  45. FileContents contents = service.get(key);
  46. InputStream in = contents.getInputStream();
  47. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  48. title = reader.readLine();
  49. }
  50. catch (FileNotFoundException e)
  51. {
  52. title =
  53. JOptionPane.showInputDialog("Please supply a frame title:");
  54. if (title == null) return;
  55. service.create(key, 100);
  56. FileContents contents = service.get(key);
  57. OutputStream out = contents.getOutputStream(true);
  58. PrintStream printOut = new PrintStream(out);
  59. printOut.print(title);
  60. }
  61. setTitle(title);
  62. }
  63. catch (UnavailableServiceException e)
  64. {
  65. JOptionPane.showMessageDialog(this, e);
  66. }
  67. catch (MalformedURLException e)
  68. {
  69. JOptionPane.showMessageDialog(this, e);
  70. }
  71. catch (IOException e)
  72. {
  73. JOptionPane.showMessageDialog(this, e);
  74. }
  75. }
  76. /**
  77. * Открывает файл предыстории и обновляет отображаемый данные
  78. */
  79. public void open()
  80. {
  81. try
  82. {
  83. FileOpenService service = (FileOpenService) ServiceManager.lookup("javax.jnlp.FileOpenService");
  84. FileContents contents = service.openFileDialog(".", new String[] { "txt" });
  85. JOptionPane.showMessageDialog(this, contents.getName());
  86. if (contents != null)
  87. {
  88. InputStream in = contents.getInputStream();
  89. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  90. String line;
  91. while ((line = reader.readLine()) != null)
  92. {
  93. panel.append(line);
  94. panel.append("\n");
  95. }
  96. }
  97. }
  98. catch (UnavailableServiceException e)
  99. {
  100. JOptionPane.showMessageDialog(this, e);
  101. }
  102. catch (IOException e)
  103. {
  104. JOptionPane.showMessageDialog(this, e);
  105. }
  106. }
  107. /**
  108. * Сохраняет предысторию калькуляций в файле
  109. */
  110. public void save()
  111. {
  112. try
  113. {
  114. ByteArrayOutputStream out = new ByteArrayOutputStream();
  115. PrintStream printOut = new PrintStream(out);
  116. printOut.print(panel.getText());
  117. InputStream data = new ByteArrayInputStream(out.toByteArray());
  118. FileSaveService service = (FileSaveService) ServiceManager.lookup("javax.jnlp.FileSaveService");
  119. service.saveFileDialog(".", new String[] { "txt" }, data, "calc.txt");
  120. }
  121. catch (UnavailableServiceException e)
  122. {
  123. JOptionPane.showMessageDialog(this, e);
  124. }
  125. catch (IOException e)
  126. {
  127. JOptionPane.showMessageDialog(this, e);
  128. }
  129. }
  130. }
Листинг программы
  1. package webstart;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.awt.event.ActionEvent;
  5. import java.awt.event.ActionListener;
  6. /**
  7. * Created by Михаил on 03.08.2016.
  8. */
  9. public class CalculatorPanel extends JPanel {
  10. public CalculatorPanel() {
  11. setLayout(new BorderLayout());
  12. result = 0;
  13. lastCommand = "=";
  14. start=true;
  15. display = new JButton("Вводи");
  16. display.setEnabled(false);
  17. add(display, BorderLayout.NORTH);
  18. ActionListener insert = new InsertAction();
  19. ActionListener command = new CommandAction();
  20. panel = new JPanel();
  21. panel.setLayout(new GridLayout(4, 4));
  22. addButton("7", insert);
  23. addButton("8", insert);
  24. addButton("9", insert);
  25. addButton("/", command);
  26. addButton("4", insert);
  27. addButton("5", insert);
  28. addButton("6", insert);
  29. addButton("*", command);
  30. addButton("1", insert);
  31. addButton("2", insert);
  32. addButton("3", insert);
  33. addButton("-", command);
  34. addButton("0", insert);
  35. addButton(".", insert);
  36. addButton("=", command);
  37. addButton("+", command);
  38. add(panel, BorderLayout.CENTER);
  39. }
  40. /**
  41. * Вводит кнопку на центральной панели
  42. * @param label Метка кнопки
  43. * @param listener Приемник действий кнопки
  44. */
  45. private void addButton(String label, ActionListener listener) {
  46. JButton button = new JButton(label);
  47. button.addActionListener(listener);
  48. panel.add(button);
  49. }
  50. /**
  51. * При обработке событий строка действия кнопки вводится
  52. * в конце отображаемого текста
  53. */
  54. private class InsertAction implements ActionListener
  55. {
  56. public void actionPerformed(ActionEvent event)
  57. {
  58. String input = event.getActionCommand();
  59. if(start) {
  60. display.setText("");
  61. start = false;
  62. }
  63. display.setText(display.getText() + input);
  64. }
  65. }
  66. /**
  67. * При обработке событий выполняется команда,
  68. * указанная в строке действия кнопки
  69. */
  70. private class CommandAction implements ActionListener
  71. {
  72. public void actionPerformed(ActionEvent event)
  73. {
  74. String command = event.getActionCommand();
  75. if(start)
  76. {
  77. if(command.equals("-"))
  78. {
  79. display.setText(command);
  80. start = false;
  81. }
  82. else lastCommand = command;
  83. }
  84. else
  85. {
  86. calculate(Double.parseDouble(display.getText()));
  87. lastCommand = command;
  88. start=true;
  89. }
  90. }
  91. }
  92. /**
  93. * Выполняет ожидающую калькуляцию
  94. * @param x Значение, накапливаемое с учетом предыдущего результата
  95. */
  96. public void calculate(double x)
  97. {
  98. if(lastCommand.equals("+")) result += x;
  99. else if(lastCommand.equals("-")) result -= x;
  100. else if(lastCommand.equals("*")) result *= x;
  101. else if(lastCommand.equals("/")) result /= x;
  102. else if(lastCommand.equals("=")) result = x;
  103. display.setText("" + result);
  104. }
  105. private JButton display;
  106. private JPanel panel;
  107. private double result;
  108. private String lastCommand;
  109. private boolean start;
  110. }

Решение задачи: «StringBuilder»

textual
Листинг программы
  1. private CalculatorPanel panel;
  2. panel.append(line);
  3. panel.append("\n");

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


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

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

14   голосов , оценка 4.143 из 5

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

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

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