var (
value1, value2 float64
)
for value1 < 9 || value2 < 9 || value1 < 9 && value2 < 9 {
fmt.Print("Masukan berat belanjaan di dalam kantong : ")
fmt.Scan(&value1, &value2)
}
fmt.Println("Program Selesai")
I want the program does looping to show inputs from the user and stop when one of the two inputs is less than 9. But the program always stops when both of value is more than or equals 9. Help me to fix it.
I recommend using a function:
func input(value *float64) bool {
fmt.Print("Enter the weight of the grocery in the bag (less than 9 ends the loop):")
_, err := fmt.Scan(value)
if err != nil {
log.Fatal(err)
}
fmt.Println("You entered:", *value)
return *value >= 9.0
}
Which makes your main loop very clean:
for input(&value1) && input(&value2) {
}
You may try this:
package main
import (
"fmt"
"log"
)
func main() {
value1, value2 := 0.0, 0.0
for input(&value1) && input(&value2) {
}
fmt.Println("Done.")
}
func input(value *float64) bool {
fmt.Print("Enter the weight of the grocery in the bag (less than 9 ends the loop):")
_, err := fmt.Scan(value)
if err != nil {
log.Fatal(err)
}
fmt.Println("You entered:", *value)
return *value >= 9.0
}
Output:
Enter the weight of the grocery in the bag (less than 9 ends the loop):12
You entered: 12
Enter the weight of the grocery in the bag (less than 9 ends the loop):7
You entered: 7
Done.
You may initialize values to a number like 9.0
or greater, so you don't need to use the break
:
value1, value2 := 9.0, 9.0
for value1 >= 9 && value2 >= 9 {
fmt.Print("Masukan berat belanjaan di dalam kantong : ")
fmt.Scan(&value1, &value2)
}
And check for errors, e.g.:
if _, err := fmt.Scan(&value1, &value2); err != nil {
panic(err)
}
stop when one of two input is less than 9.
For example,
package main
import "fmt"
func main() {
var (
value1, value2 float64
)
for {
fmt.Print("Masukan berat belanjaan di dalam kantong : ")
n, err := fmt.Scan(&value1, &value2)
if n == 2 && err == nil {
if value1 < 9 || value2 < 9 {
break
}
}
}
fmt.Println("Program Selesai")
}
You need to change the sign in your code from <
to >
.
The conditional is backwards. It should be read as "do a for loop while value1 or value2 is greater than 9". That's when you want the for loop to execute.
If this is for a class, make sure you actually understand what's going on so you will learn.