Help with if else statement


(Raul Gauna) #1

Good afternoon,

I’m fairly new to programing in general, and i wrote a simple program to calculate a value based on the user’s input. the goal is to have a certain calculation if its less than or equal to 12, and a different calculation if it’s greater than 12.

I managed to get this working, but there’s a problem. it doesn’t take into account if the user is typing in a character…example…if the user types “hello”, the program just closes. what i’m trying to do is simple…if the user types hello, i want the output to say “please type a valid number.” and it’ll repeat the process until a valid number is reached.

how do I go about doing this?

here’s the code i have:

package main

import (
"fmt"
"os"
"bufio"
)

func main(){
	var value float64
	fmt.Println("Enter the value: ")
	fmt.Scanln(&value)
	if value <=12{
		fmt.Println(value*4.3 + 18)
	} else{
		fmt.Println(value*5.0 + 9.7)
	}
	fmt.Println("Press 'Enter' to exit program...")
    bufio.NewReader(os.Stdin).ReadBytes('\n') 
}

(Yamil Bracho) #2

You can get the error returned by Scanl. For example

if _, err := fmt.Scanln(&value); err != nil {
fmt.Println(err)
}
// No Error,


(Raul Gauna) #3

this worked, but it terminates the program. is there a way i can convert this into a for loop so that it can keep asking for user input until a number is typed?


(Yamil Bracho) #4

Absolutely!!!
You can add a for with a boolean flag to exit. For example
okFlag := true
for okFlag {

if _, err := fmt.Scanln(&value); err != nil {
okFlag := false;
break;
}
// No Error,


(Ignacio Gómez) #5

That’s wrong, the flag is unnecessary and you’re breaking on error, not on success.
You may use Scanln or Scanf to specify that you want a float, e.g.:

func main() {
	var value float64
	fmt.Println("Enter the value: ")
	for {
		_, err := fmt.Scanln(&value)
		//This works too.
		//_, err := fmt.Scanf("%f", &value)
		if err == nil {
			break
		}
	}
	if value <= 12 {
		fmt.Println(value*4.3 + 18)
	} else {
		fmt.Println(value*5.0 + 9.7)
	}
}


(Raul Gauna) #6

this almost works…i tested it out and typed 34gy4q4

the result was:

35.2
Press ‘Enter’ to exit program…

if whatever i type ends with a letter, it’ll repeat the loop, but if it ends with a number, it looks like it reads the last sequential numbers and processes that in the if statements.


(Ignacio Gómez) #7

That’s true, I forgot about that. You may avoid this by scanning to a string and explicitly parsing it to a float, like this:

func main() {
	var s string
	var value float64
	fmt.Println("Enter the value: ")
	for {
		_, err := fmt.Scanln(&s)
		if err == nil {
			value, err = strconv.ParseFloat(s, 64)
			if err == nil {
				break
			}
		}
	}
	if value <= 12 {
		fmt.Println(value*4.3 + 18)
	} else {
		fmt.Println(value*5.0 + 9.7)
	}
}

(Raul Gauna) #8

This is perfect! Thank you so much for your help!