Switch

    Go

    1. package main
    2.  
    3. import (
    4. "fmt"
    5. "strconv"
    6. )
    7.  
    8. func str2int(s string) int {
    9. i, err := strconv.Atoi(s)
    10. if err != nil {
    11. panic("Not a number")
    12. }
    13. return i
    14. }
    15. func main() {
    16. var number_string string
    17. fmt.Scanln(&number_string)
    18. number := str2int(number_string)
    19.  
    20. switch number {
    21. case 8:
    22. fmt.Println("Oxygen")
    23. case 1:
    24. fmt.Println("Hydrogen")
    25. case 2:
    26. fmt.Println("Helium")
    27. case 11:
    28. fmt.Println("Sodium")
    29. default:
    30. fmt.Printf("I have no idea what %d is\n", number)
    31.  
    32. // Alternative solution
    33.  
    34. fmt.Scanln(&number_string)
    35. db := map[int]string{
    36. 1: "Hydrogen",
    37. 2: "Helium",
    38. 8: "Oxygen",
    39. 11: "Sodium",
    40. }
    41. number = str2int(number_string)
    42. if name, exists := db[number]; exists {
    43. fmt.Println(name)
    44. } else {
    45. fmt.Printf("I have no idea what %d is\n", number)
    46. }
    47. }