-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
74 lines (66 loc) · 2.78 KB
/
Copy pathCalculator.java
File metadata and controls
74 lines (66 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.ArrayList;
import java.util.Scanner;
public class Calculator {
// Список для хранения истории операций
private static ArrayList<String> history = new ArrayList<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean run = true;
System.out.println("=== Калькулятор с историей ===");
System.out.println("Доступные операции: +, -, *, /");
System.out.println("Команды: 'history' - показать историю, 'exit' - выход");
while (run) {
System.out.println("\nВведите выражение (например: 2 + 2): ");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
run = false;
System.out.println("До свидания!");
} else if (input.equalsIgnoreCase("history")) {
showHistory();
} else {
try {
double result = calculateExpression(input);
System.out.println("Результат: " + result);
history.add(input + " = " + result);
} catch (Exception e) {
System.out.println("Ошибка!");
}
}
}
scanner.close();
}
// Метод для вычисления выражений
private static double calculateExpression(String input) {
String[] parts = input.split("(?=[-+*/])|(?<=[-+*/])");;
if (parts.length != 3) {
throw new IllegalArgumentException("Неверный формат");
}
double a = Double.parseDouble(parts[0]);
String operator = parts[1];
double b = Double.parseDouble(parts[2]);
switch (operator) {
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
if (b == 0) throw new ArithmeticException("Деление на ноль.");
return a / b;
default:
throw new UnsupportedOperationException("Неизвестная операция");
}
}
// Метод для показа истории
private static void showHistory() {
if (history.isEmpty()) {
System.out.println("История пуста.");
} else {
System.out.println("\n=== Bcnjhbz jgthfwbq ===");
for (int i = 0; i < history.size(); i++) {
System.out.println((i + 1) + ". " + history.get(i));
}
}
}
}