top of page
Search

Go Code: Hello World with Dice Rolls

## Go Code: Hello World with Dice Rolls


This program demonstrates a simple dice rolling simulation in Go. It prompts the user for the number of rolls (between 4 and 6), then simulates rolling six dice for each round and displays the results.  Input validation ensures the user provides a valid number of rolls.


```go

package main


import (

        "fmt"

        "math/rand"

        "time"

)


func rollDice() int {

        return rand.Intn(6) + 1 // Returns a random number between 1 and 6

}


func main() {

        rand.Seed(time.Now().UnixNano()) // Seed the random number generator


        var numRolls int


        for {

                fmt.Print("How many rolls would you like (4-6)? ")

                _, err := fmt.Scanln(&numRolls)


                if err != nil || numRolls < 4 || numRolls > 6 {

                        fmt.Println("Invalid input. Please enter a number between 4 and 6.")

            // Clear the input buffer (important for preventing infinite loops on bad input)

            fmt.Scanln() // Read and discard the rest of the line

                        continue

                }

                break // Valid input, exit the loop

        }


        results := make([][]int, numRolls) // 2D slice to store results


        for i := 0; i < numRolls; i++ {

                results[i] = make([]int, 6)

                fmt.Printf("Roll %d: ", i+1)

                for j := 0; j < 6; j++ {

                        results[i][j] = rollDice()

                        fmt.Printf("%d ", results[i][j])

                }

                fmt.Println()

        }

}

```


Key improvements and explanations in the Go version:


  *Random Number Seeding:** `rand.Seed(time.Now().UnixNano())` seeds the random number generator using the current time. This is essential for generating different random sequences each time the program runs.


  *Input Validation:** The `for` loop continues to prompt the user until valid input is given.  It checks for errors during input using `fmt.Scanln` and if the number is within the valid range.


  *Clearing Input Buffer:** The `fmt.Scanln()` after the error message is crucial.  If the user enters bad input (like letters), the input remains in the buffer, and without clearing it, the next `fmt.Scanln(&numRolls)` will immediately try to read the same bad input again, creating an infinite loop.


  *2D Slice:** The `results` are stored in a 2D slice (`[][]int`).  This is Go's equivalent of a dynamic array or vector.


  *Clearer Output:** The output is formatted to clearly show each roll and its individual dice values.


  *Error Handling:** The `if err != nil` part of the input validation loop handles cases where `fmt.Scanln` encounters an error (e.g., the user enters non-numeric input).  This prevents the program from crashing.



This Go code provides a robust and functional dice rolling simulation, incorporating best practices for random number generation and input handling.

 
 
 

Recent Posts

See All
What we can learn from cats

That's a fascinating observation, and you've touched upon something quite profound about the apparent inner peace that some animals seem...

 
 
 

Commentaires


Post: Blog2_Post

Subscribe Form

Thanks for submitting!

©2020 by LearnTeachMaster DevOps. Proudly created with Wix.com

bottom of page