Home > Net >  I have been trying to print out this code, and it keeps popping out an error
I have been trying to print out this code, and it keeps popping out an error

Time:06-29

I've been trying to print this out, but keeps popping out an error message..

package main

import "fmt"

func main() {

for i:= 1; i<= 100; i   
switch i {
case i % 15 == 0: 
fmt.Println("FizzyBuzz") 
case i % 3 == 0: 
fmt.Println("Fizzy") 
case i % 5 == 0: 
fmt.Println("Buzz") 
default : 
fmt.Println(i)
}

}

This is the code......

CodePudding user response:

There are two issues with your code.

First of all, the for statement is missing its opening and closing curly brackets.

Then, the usage of the switch statement is wrong. You are, in fact, supposed to specify a value for the i variable for each of the cases that you want to evaluate. If you want to evaluate conditions (for example, i % 15 == 0), the if-else statement will be the right choice.

The code would then be like as follows:

package main

import "fmt"

func main() {

    for i:= 1; i<= 100; i   {
        if i % 15 == 0 {
            fmt.Println("FizzyBuzz")
        } else if i % 3 == 0 {
            fmt.Println("Buzz")
        } else if i % 5 == 0 {
            fmt.Println("Buzz") 
        } else {
            fmt.Println(i)
        }
     }
}

CodePudding user response:

You are trying to add a bool values to the case statements, the case statements expects a value wit with the same type as the comparison variable at the switch statement [ Here you passed i, which is integer ] and you passed a boolean to the case statements. I would recommend to use if else here instead of switch case.

Please checkout this link for more information about switch case statement in Golang here

  •  Tags:  
  • go
  • Related