-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
84 lines (75 loc) · 2.72 KB
/
Main.java
File metadata and controls
84 lines (75 loc) · 2.72 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
75
76
77
78
79
80
81
82
83
84
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
String choice = "";
do {
printMenu();
choice = choice();
switch (choice) {
case "1":
String firstNum = enterNum();
String secondNum = enterNum();
String sign = enterSign();
calculate(calculator, firstNum, secondNum, sign);
break;
case "2":
System.out.println("end");
break;
}
} while (!choice.equals("2"));
}
private static void calculate(Calculator calculator,
String firstNum,
String secondNum,
String sign) {
NumLinkedList result = null;
switch (sign) {
case "+":
result = calculator.performCalculation(firstNum, secondNum, Sign.PLUS);
break;
case "-":
result = calculator.performCalculation(firstNum, secondNum, Sign.MINUS);
break;
case "*":
result = calculator.performCalculation(firstNum, secondNum, Sign.MULTIPLY);
break;
}
System.out.printf("%s %s %s = %s\n", firstNum, sign, secondNum, result);
}
private static String enterNum() {
String numPattern = "-?[0-9]+";
System.out.println("Enter number: ");
Scanner scanner = new Scanner(System.in);
String num = scanner.nextLine();
while (!num.matches(numPattern)) {
System.out.println("Number contains only digits and can optionally start with a minus sign!!!");
num = scanner.nextLine();
}
return num;
}
private static String enterSign() {
String signs = "[-+*]";
System.out.println("Enter sign (+, - or *):");
Scanner scanner = new Scanner(System.in);
String sign = scanner.nextLine();
while (!sign.matches(signs)) {
System.out.println("please enter -, + or *");
sign = scanner.nextLine();
}
return sign;
}
private static String choice() {
String choicePattern = "[12]";
Scanner scanner = new Scanner(System.in);
String choice = scanner.nextLine();
while (!choice.matches(choicePattern)) {
System.out.println("Please enter 1 or 2.");
choice = scanner.nextLine();
}
return choice;
}
private static void printMenu() {
System.out.println("1./ Enter two numbers then sign.\n2./End");
}
}