-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
61 lines (56 loc) · 1.77 KB
/
Calculator.java
File metadata and controls
61 lines (56 loc) · 1.77 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
import java.util.Scanner;
public class Calculator {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int num1 = getInt();
int num2 = getInt();
char operation = getOperation();
int result = calc(num1,num2,operation);
System.out.println("Result: "+result);
}
public static int getInt(){
System.out.println("Enter a number:");
int num;
if(scanner.hasNextInt()){
num = scanner.nextInt();
} else {
System.out.println("You made an error when entering a number. Try again.");
scanner.next();
num = getInt();
}
return num;
}
public static char getOperation(){
System.out.println("Введите операцию:");
char operation;
if(scanner.hasNext()){
operation = scanner.next().charAt(0);
} else {
System.out.println("You made an error when entering a number. Try again.");
scanner.next();//рекурсия
operation = getOperation();
}
return operation;
}
public static int calc(int num1, int num2, char operation){
int result;
switch (operation){
case '+':
result = num1+num2;
break;
case '-':
result = num1-num2;
break;
case '*':
result = num1*num2;
break;
case '/':
result = num1/num2;
break;
default:
System.out.println("The operation was not recognized. Repeat the entry.");
result = calc(num1, num2, getOperation());
}
return result;
}
}