-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calc.java
73 lines (65 loc) · 2.12 KB
/
Calc.java
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
import java.util.Scanner;
import static java.lang.Integer.decode;
import static java.lang.Integer.parseInt;
public class Calc {
private Scanner scan = new Scanner(System.in);
private final char ARAB_FORMAT = 'A';
private final char ROME_FORMAT = 'R';
private int firstArg, secondArg;
private char operation;
private char format;
public String request()
{
System.out.println("Введите выражение");
String expres = scan.nextLine();
String[] expres_mas = expres.split("(?!^)\\b");
treatment(expres_mas);
return calculate();
}
private void treatment(String[] expr){
expr[0] = expr[0].trim();
expr[1] = expr[1].trim();
expr[2] = expr[2].trim();
if ((expr.length == 3) && expr[1].matches("\\*|/|\\+|-"))
{
operation = expr[1].charAt(0);
if (Roman.isRoman(expr[0]) && Roman.isRoman(expr[2])) {
firstArg = Roman.romanToArabic(expr[0]);
secondArg = Roman.romanToArabic(expr[2]);
format = ROME_FORMAT;
}else if (expr[0].matches("[1-9]|10")&& expr[2].matches("[1-9]|10")){
firstArg = parseInt(expr[0]);
secondArg = parseInt(expr[2]);
format = ARAB_FORMAT;
}else {
throw new InputException("incorrect input");
}
} else {
throw new InputException("incorrect input");
}
}
private String calculate()
{
double result = 0;
switch (operation)
{
case '+':
result = firstArg+secondArg;
break;
case '-':
result = firstArg-secondArg;
break;
case '*':
result = firstArg*secondArg;
break;
case '/':
result = (double) firstArg/secondArg;
break;
}
if(format=='A'){
return String.valueOf((int) result);
} else {
return String.valueOf((Roman.arabicToRoman((int) result)));
}
}
}