Skip to content

Commit

Permalink
Merge pull request #458 from EgorBurov246/features/lab22
Browse files Browse the repository at this point in the history
Лабораторная работа №22
  • Loading branch information
Pastor authored Nov 1, 2024
2 parents f1fe25a + 88ab391 commit 57a1c36
Show file tree
Hide file tree
Showing 7 changed files with 262 additions and 0 deletions.
13 changes: 13 additions & 0 deletions students/23K0815/23K0815-p22/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>23K0815</artifactId>
<groupId>ru.mirea.practice</groupId>
<version>2024.1</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>23K0815-p22</artifactId>
<description>Массивы</description>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package ru.mirea.practice.s0000001.task1;

import java.util.Scanner;
import java.util.Stack;

public abstract class RpnCalculator {

public static double evaluate(String expression) {
Stack<Double> stack = new Stack<>();

// Разделяем входную строку на элементы
String[] tokens = expression.split(" ");

for (String token : tokens) {
switch (token) {
case "+":
stack.push(stack.pop() + stack.pop());
break;
case "-":
double subtrahend = stack.pop();
double minuend = stack.pop();
stack.push(minuend - subtrahend);
break;
case "*":
stack.push(stack.pop() * stack.pop());
break;
case "/":
double divisor = stack.pop();
double dividend = stack.pop();
stack.push(dividend / divisor);
break;
default:
// Если токен не оператор, то предполагаем, что это число
stack.push(Double.parseDouble(token));
break;
}
}

// Результат будет единственным элементом в стеке
return stack.pop();
}

public static void main(String[] args) {
// Используем try-with-resources для безопасного закрытия Scanner
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Введите выражение в обратной польской нотации (RPN): ");

String expression = scanner.nextLine();

if (expression != null && !expression.trim().isEmpty()) {
try {
double result = evaluate(expression);
System.out.println("Результат: " + result);
} catch (Exception e) {
System.out.println("Ошибка: " + e.getMessage());
}
} else {
System.out.println("Вы не ввели выражение.");
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package ru.mirea.practice.s0000001.task2;

import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CalculatorController {
private final CalculatorModel model; // Instance variable
private final CalculatorView view; // Instance variable

public CalculatorController(CalculatorModel model, CalculatorView view) {
this.model = model;
this.view = view;

this.view.addCalculateListener(new CalculateListener());
this.view.addNumberButtonListener(new NumberButtonListener());
this.view.addOperationButtonListener(new OperationButtonListener());
}

private class CalculateListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String input = view.getInput();
try {
double result = model.evaluate(input);
view.setResult("Результат: " + result);
} catch (Exception ex) {
view.setResult("Ошибка: " + ex.getMessage());
}
}
}

private class NumberButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
view.setInput(view.getInput() + source.getText());
}
}

private class OperationButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
String operation = source.getText();
if ("C".equals(operation)) {
view.setInput("");
} else {
view.setInput(view.getInput() + " " + operation + " ");
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package ru.mirea.practice.s0000001.task2;

import java.util.Stack;

public class CalculatorModel {
public double evaluate(String expression) {
Stack<Double> stack = new Stack<>();
String[] tokens = expression.trim().split("\\s+");

for (String token : tokens) {
switch (token) {
case "+":
stack.push(stack.pop() + stack.pop());
break;
case "-":
double subtrahend = stack.pop();
double minuend = stack.pop();
stack.push(minuend - subtrahend);
break;
case "*":
stack.push(stack.pop() * stack.pop());
break;
case "/":
double divisor = stack.pop();
double dividend = stack.pop();
stack.push(dividend / divisor);
break;
default:
stack.push(Double.parseDouble(token));
break;
}
}
return stack.pop();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package ru.mirea.practice.s0000001.task2;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.GridLayout;
import java.awt.event.ActionListener;

public class CalculatorView {
private final JTextField inputField;
private final JTextArea resultArea;
private final JButton[] numberButtons;
private final JButton[] operationButtons;
private final JButton calculateButton;
private final String[] operations = {"+", "-", "*", "/", "C"};

public CalculatorView() {
final JFrame frame = new JFrame("RPN Calculator"); // Объявление как final и инициализация
inputField = new JTextField(20);
resultArea = new JTextArea(10, 30);
calculateButton = new JButton("Вычислить");

numberButtons = new JButton[10];
for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
}

operationButtons = new JButton[operations.length];
for (int i = 0; i < operations.length; i++) {
operationButtons[i] = new JButton(operations[i]);
}

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 4));

panel.add(new JLabel("Введите выражение (RPN):"));
panel.add(inputField);
panel.add(calculateButton);
panel.add(resultArea);

for (JButton numberButton : numberButtons) {
panel.add(numberButton);
}

for (JButton operationButton : operationButtons) {
panel.add(operationButton);
}

resultArea.setEditable(false);
frame.add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Первое использование переменной frame
}

public String getInput() {
return inputField.getText();
}

public void setInput(String input) {
inputField.setText(input);
}

public void setResult(String result) {
resultArea.setText(result);
}

public void addCalculateListener(ActionListener listenForCalcButton) {
calculateButton.addActionListener(listenForCalcButton);
}

public void addNumberButtonListener(ActionListener listener) {
for (JButton numberButton : numberButtons) {
numberButton.addActionListener(listener);
}
}

public void addOperationButtonListener(ActionListener listener) {
for (JButton operationButton : operationButtons) {
operationButton.addActionListener(listener);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package ru.mirea.practice.s0000001.task2;

public abstract class RpnCalculatorApp {
public static void main(String[] args) {
// Create instances of the model and view
CalculatorModel model = new CalculatorModel();
CalculatorView view = new CalculatorView();

// Create the controller
new CalculatorController(model, view);
}
}
1 change: 1 addition & 0 deletions students/23K0815/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,6 @@
<module>23K0815-p19</module>
<module>23K0815-p20</module>
<module>23K0815-p21</module>
<module>23K0815-p22</module>
</modules>
</project>

0 comments on commit 57a1c36

Please sign in to comment.