forked from waboke/calculator_app_java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainCalculator.java
More file actions
88 lines (66 loc) · 3.07 KB
/
Copy pathMainCalculator.java
File metadata and controls
88 lines (66 loc) · 3.07 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
85
86
87
88
import java.util.Scanner;
// Ajibade Caleb
// Computer Science
// U22CS1020
class Maincalculator{
public static void main(String[] args) {
String[] userInfo = userInput();
String firstNumber = userInfo[0];
String secondNumber = userInfo[1];
String operator = userInfo[2];
calculationLogic(operator, firstNumber, secondNumber);
}
static void calculationLogic(String operator, String firstNumber, String secondNumber) {
try {
float firstNumberInput = Float.valueOf(firstNumber);
float secondNumberInput = Float.valueOf(secondNumber);
float calculation;
switch (operator) {
case "+":
calculation = firstNumberInput + secondNumberInput;
System.out.print(firstNumber + " + " + secondNumber + " = " + calculation);
break;
case "-":
calculation = firstNumberInput + secondNumberInput;
System.out.print(firstNumber + " + " + secondNumber + " = " + calculation);
break;
case "*":
calculation = firstNumberInput + secondNumberInput;
System.out.print(firstNumber + " + " + secondNumber + " = " + calculation);
break;
case "/":
if (secondNumberInput == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}else {
calculation = firstNumberInput / secondNumberInput;
System.out.print(firstNumber + " / " + secondNumber + " = " + calculation);
}
break;
case "=":
boolean equals = firstNumberInput == secondNumberInput;
if (equals == true) {
System.out.print(firstNumber + " = " + secondNumber );
} else {
System.out.print(firstNumber + " != " + secondNumber );
}
break;
default:
throw new IllegalArgumentException("Invalid operator. Use +, -, *, or /");
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("Error: The number you provided cannot be used");
}
}
public static String[] userInput() {
Scanner scanner = new Scanner(System.in);
System.out.println("Input first number");
String firstNumber = scanner.nextLine();
System.out.println("Input second number");
String secondNumber = scanner.nextLine();
System.out.println("Input operation");
String operator = scanner.nextLine();
scanner.close();
return new String[]{firstNumber, secondNumber, operator};
}
}