From e56ec312f6f0c57c6530c5e4a81a5cf168f1e989 Mon Sep 17 00:00:00 2001 From: raul Date: Sat, 20 Jan 2024 12:23:39 +0100 Subject: [PATCH] Organized code and improved error handling Added really primitive error handling to numStar scanning, I really have to figure out how to properly handle errors in Golang beyond abusing if/else and switch/case --- star-shapes/go.mod | 3 +++ star-shapes/main.go | 53 +++++++++++++++++-------------------------- star-shapes/shapes.go | 34 +++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 32 deletions(-) create mode 100644 star-shapes/go.mod create mode 100644 star-shapes/shapes.go diff --git a/star-shapes/go.mod b/star-shapes/go.mod new file mode 100644 index 0000000..c314abc --- /dev/null +++ b/star-shapes/go.mod @@ -0,0 +1,3 @@ +module star-shapes + +go 1.21.6 diff --git a/star-shapes/main.go b/star-shapes/main.go index c807c62..a4410da 100644 --- a/star-shapes/main.go +++ b/star-shapes/main.go @@ -11,11 +11,28 @@ func main() { var numShape int // TODO: Add error handling for star number - fmt.Println("How many stars do you want?") - fmt.Printf(" Stars: ") - fmt.Scan(&numStar) +forStars: + for { - fmt.Printf("\n") + fmt.Println("How many stars do you want?") + fmt.Printf(" Stars: ") + fmt.Scan(&numStar) + + // This is confusing + // switch v := interface{}(numStar).(type) { + // case int: + // break forStars + // default: + // fmt.Printf("ERROR, %v is invalid input", v) + // panic("ERROR") + // } + + if numStar >= 0 { + break forStars + } else { + fmt.Printf("\n[-] INVALID NUMBER\n\n") + } + } forShapes: for { @@ -38,31 +55,3 @@ forShapes: } } } - -func line(num int) { - for i := 0; i < num; i++ { - fmt.Printf("* ") - } - fmt.Printf("\n") -} - -func square(num int) { - for i := 0; i < num; i++ { - for i := 0; i < num; i++ { - fmt.Printf("* ") - } - fmt.Printf("\n") - } -} - -func flag(num int) { - for a := 0; a < num; a++ { - for i := -1; i < a; i++ { - fmt.Printf("* ") - } - fmt.Printf("\n") - } - for i := 0; i < num/2; i++ { - println("*") - } -} diff --git a/star-shapes/shapes.go b/star-shapes/shapes.go new file mode 100644 index 0000000..f62cdb6 --- /dev/null +++ b/star-shapes/shapes.go @@ -0,0 +1,34 @@ +package main + +import "fmt" + +// Drawing a line of asterisks +func line(num int) { + for i := 0; i < num; i++ { + fmt.Printf("* ") + } + fmt.Printf("\n") +} + +// Drawing a square of asterisks +func square(num int) { + for i := 0; i < num; i++ { + for i := 0; i < num; i++ { + fmt.Printf("* ") + } + fmt.Printf("\n") + } +} + +// Drawing a flag of asterisks +func flag(num int) { + for a := 0; a < num; a++ { + for i := -1; i < a; i++ { + fmt.Printf("* ") + } + fmt.Printf("\n") + } + for i := 0; i < num/2; i++ { + println("*") + } +}