Hi,
I am fairly new to go and just work on my first project, which has gotten along quite well so far. However, I have a strange problem now with validation of map keys. I am trying to create a simple flash card app, that asks for a card and then for a definition. If either the card or the definition exist already, it should throw an error and let the user enter the term again. This is my code (I have cut unnecessary cases out):
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
fmt.Println("Flash Cards v. 1.0")
var choice string
var card string
var definition string
cards := make(map[string]string)
for {
fmt.Println("Input the desired action (add, remove, import, export, ask, exit):")
fmt.Scan(&choice)
switch choice {
case "add":
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
for {
fmt.Println("The card: ")
scanner.Scan()
card = scanner.Text()
if _, ok := cards[card]; ok {
fmt.Printf("The card %s already exists. Try again:\n", card)
scanner.Scan()
card = scanner.Text()
}
fmt.Println("The definition for the card:")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
definition = scanner.Text()
if _, ok := cards[definition]; ok {
fmt.Printf("The definition %s already exists. Try again:\n", definition)
scanner.Scan()
definition = scanner.Text()
}
cards[card] = definition
fmt.Printf("The pair %q:%q has been added\n", card, definition)
break
}
case "remove":
case "import":
case "export":
case "ask":
case "exit":
default:
fmt.Println("Error. Please try again!")
}
}
}
The program runs fine. I enter add. It asks to enter a card, so for example, I enter France. Then it asks for a definition, and I enter Paris. I get the message The pair France:Paris has been added and get back to the menu, enter add again, and it asks for a card. If I now enter France again, I get the error saying The card France already exists. Try again. so if I now enter Germany it does accept the entry and asks for a term/definition. But if I now enter Paris again, it says The pair Spain:Paris has been added.
Instead, it should be giving a warning, saying that the definition Paris already exists and then ask the user to enter a new term, as it does above with Paris. I have been looking at the code and at various sources and docs, but I couldn’t figure it out. I am sure it is some minor issue, I am not considering.
Any help would be appreciated.
Cheers,
Ben