Hello I am sort of this don’t have an idea what to code guy, so I thought I try myself at the state design pattern… Well got something out yet it is far from the design pattern. This is okay, what I don’t understand is why the program doesn’t read the second input from the console which I tell it to do in the method SetValues() of the calculator structure. Should I use a slice reader approach?
[I excuse myself for bad formatting if this is the case.]
code in the package:
package vect
import "fmt"
import "bufio"
import "os"
type Values struct{
a,b,c int
}
func (v *Values) Loadval(a,b,c int) {
v.a = a
v.b= b
v.c = c
}
func (v Values) Print(){
fmt.Println(v.a,v.b,v.c)
}
type Programstate interface{
Load(v Values)
Display()
Calculate()
Control() (bool,bool)
}
type Additor struct{
val Values
calc *Programstate
}
func (c *Additor) Load(v Values) {
c.val.a = v.a
c.val.b = v.b
c.val.c = v.c
}
func (c *Additor) Calculate(){
c.val.c = c.val.a + c.val.b
}
func (c Additor) Display() {
fmt.Println(c.val)
}
func (c Additor) Control() (bool,bool){
fmt.Println("New calculation? (y/n)")
fmt.Println("No entry for ending program")
reader := bufio.NewReader(os.Stdin)
text, _ ,_:= reader.ReadRune()
fmt.Println(text)
if text == 'y'{
return true, true
}
if text == 'n'{
return false, true
}
return false, false
}
type Calculator struct{
calc Programstate
add Additor
}
func (c *Calculator) StartUp(){
c.calc = &c.add
}
func (c *Calculator) Switch() bool{
fmt.Println("What calculation do you want to do next?")
fmt.Println("a for addition")
reader := bufio.NewReader(os.Stdin)
text, _ ,_:= reader.ReadRune()
if text == 'a'{
c.calc = &c.add
return true
}
return false
}
func (c *Calculator) SetValues() {
var val Values
fmt.Println("What first value do you want to calculate?")
reader := bufio.NewReader(os.Stdin)
text , _ , _ := reader.ReadRune()
val.a = int(text -'0')
fmt.Println("What second value do you want to calculate?")
text2 , _ , _ := reader.ReadRune()
val.b = int(text2 - '0')
fmt.Println("Your two values are:", val.a, val.b)
c.calc.Load(val)
}
func (c Calculator) Dostuff() bool {
c.calc.Calculate()
c.calc.Display()
i , _ := c.calc.Control()
return i
}
…
the code in main
package main
import(
"vectors"
)
func main(){
var C vect.Calculator
C.StartUp()
i := true
for i{
C.SetValues()
i=C.Dostuff()
if i == true{
i=C.Switch()
}
}
}