I'm brand new to both Go, and stack overflow so please bear with me. I'm building a simple calculator using go, and I'm trying to add functionality for floating point numbers.
the program accepts a string (ex: "2 + 3") and displays the result. It can read and calculate integers just fine, but I hit a problem when the program encounters the decimal. It uses nested switch statements once it encounters a '.' it runs the nested switch statement until it hits whitespace. It's supposed to calculate the same as the integer values, only difference is that it divides the value by 10(moving the value to the values right to the thenths hundreths thousanths etc) but when I try to run it, it just stops, no errors or anything, it just hangs there and makes me force close the program.
here's my code(my error occurs when i get to the case '.':, everything else runs fine):
package main
import (
"bufio"
"fmt"
"os"
"stack"
)
var operatorStack = stack.NewStack()
var operandStack = stack.NewStack()
func precedence(op byte) uint8 {
switch op {
case '+', '-': return 0
case '*', '/': return 1
default: panic("illegal operator")
}
}
func apply() {
op := operatorStack.Pop().(byte)
right := operandStack.Pop().(float64)
left := operandStack.Pop().(float64)
switch op {
case '+': operandStack.Push(left + right)
case '-': operandStack.Push(left - right)
case '*': operandStack.Push(left * right)
case '/': operandStack.Push(left / right)
default: panic("illegal operator")
}
}
func main() {
// Read a from Stdin.
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
line := scanner.Text()
//
for i := 0; i < len(line); {
switch line[i] {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
v := float64(0)
for {
v = v * 10 + float64(line[i] - '0')
i++
if i == len(line) || !('0' <= line[i] && line[i] <= '9') {
break
}
}
operandStack.Push(v)
case '+', '-', '*', '/':
for !operatorStack.IsEmpty() && precedence(operatorStack.Top().(byte)) >= precedence(line[i]) {
apply()
}
operatorStack.Push(line[i])
i++
case ' ': i++
case '.':
for b := line[i]; b != ' '; {
switch line[i] {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
v := float64(0)
for {
v = v / 10 + float64(line[i] - '0')
i++
if i == len(line) || !('0' <= line[i] && line[i] <= '9') {
break
}
}
operandStack.Push(v)
case ' ':
operatorStack.Push('+')
break
}
}
default: panic("illegal character")
}
}
for !operatorStack.IsEmpty() {
apply()
}
r := operandStack.Pop().(float64)
fmt.Println(r)