forked from JavaOPs/startjava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
56 lines (50 loc) · 1.54 KB
/
Calculator.java
File metadata and controls
56 lines (50 loc) · 1.54 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
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner sa = readInput("Enter first number: ");
int a = sa.nextInt();
Scanner sb = readInput("Enter second number: ");
int b = sb.nextInt();
Scanner sop = readInput("Enter operation type (+, -, *, /, ^, %): ");
String op = sop.next();
System.out.println("Result is: " + getResult(a, b, op));
}
private static Scanner readInput(String prompt) {
System.out.println(prompt);
return new Scanner(System.in);
}
private static Boolean isOpValid(String op) {
String[] opTypes = {"+", "-", "*", "/", "^", "%"};
for (String opType: opTypes) {
if (opType.equals(op)) {
return true;
}
}
return false;
}
private static int getResult(int a, int b, String op) {
if (isOpValid(op)) {
if (op.equals("+")) {
return a + b;
} else if (op.equals("-")) {
return a - b;
} else if (op.equals("*")) {
return a * b;
} else if (op.equals("/")) {
return a / b;
} else if (op.equals("^")) {
return customPow(a, b);
} else {
return a % b;
}
}
return 0;
}
private static int customPow(int a, int b) {
int result = 1;
for (int i = 0; i < b; i++) {
result *= a;
}
return result;
}
}