-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.go
66 lines (57 loc) · 1.34 KB
/
index.go
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
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
fmt.Println("This is a calculator app")
for {
// Read input from the user
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter any calculation (Example: 1 + 2 (or) 2 * 5 -> Please maintain spaces as shown in example): ")
text, _ := reader.ReadString('\n')
// Trim the newline character from the input
text = strings.TrimSpace(text)
// Check if the user entered "exit" to quit the program
if text == "exit" {
break
}
// Split the input into two parts: the left operand and the right operand
parts := strings.Split(text, " ")
if len(parts) != 3 {
fmt.Println("Invalid input. Try again.")
continue
}
// Convert the operands to integers
left, err := strconv.Atoi(parts[0])
if err != nil {
fmt.Println("Invalid input. Try again.")
continue
}
right, err := strconv.Atoi(parts[2])
if err != nil {
fmt.Println("Invalid input. Try again.")
continue
}
// Perform the calculation based on the operator
var result int
switch parts[1] {
case "+":
result = left + right
case "-":
result = left - right
case "*":
result = left * right
case "/":
result = left / right
default:
fmt.Println("Invalid operator. Try again.")
continue
}
// Print the result
fmt.Printf("Result: %d\n", result)
}
}