Hello everyone,
I am attempting the new course Golang series on Coursera and I am a bit stumped on a problem set that asks to dynamically allocate space to a slice after it reaches its original limit size of 3. Where I am having issues is that if the users decides to press ‘X’ and then enter, it exits the program. Here is my code (note I have not implemented everything yet):
// Write a program which prompts the user to enter integers and stores the integers in a sorted slice.
// The program should be written as a loop. Before entering the loop, the program should create an empty
// integer slice of size (length) 3. During each pass through the loop, the program prompts the user to enter an
// integer to be added to the slice. The program adds the integer to the slice, sorts the slice, and prints
// the contents of the slice in sorted order. The slice must grow in size to accommodate any number of integers
// which the user decides to enter. The program should only quit (exiting the loop) when the user enters the
// character ‘X’ instead of an integer.
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
userSlice := make([]int, 3) //Create a Slice of size 3
// var intToAdd rune
i := 0
for i < len(userSlice) {
fmt.Println("Welcome to Slices, Please enter a number to add to the slice:")
// fmt.Scan(&intToAdd)
inputReader := bufio.NewReader(os.Stdin)
intToAdd, _, err := inputReader.ReadRune()
if err != nil {
log.Fatal(err)
}
if intToAdd == 'X' {
fmt.Println("Thanks for using Slices!")
break
}
userSlice[i] = int(intToAdd)
fmt.Println("Slice so far:")
for _, v := range userSlice {
fmt.Println(v)
}
i++
}
}