Search code examples
vb.netconsolecasegoto

vb.net - How would I replace GoTo in this instance?


GoTo used to return to menu after a case was carried out, since its bad practice to use GoTo what else could I do? Thanks.

Menu:
            Console.WriteLine("----------------------") 
            Console.WriteLine("1 = option1")
            Console.WriteLine("2 = option2")
            Console.WriteLine("----------------------")
            Console.Write("Select an option: ")
            opts = Console.ReadLine 
            Console.WriteLine("----------------------")
                Select Case opts
                    Case 1
Happening:
                        Try 
                            Console.Write("Enter a word: ")
                            word = Console.ReadLine 
                            Select Case word.ToLower  
                               Case Eng(0)
                                    Console.WriteLine(Fre(0))
                                Case Eng(1)
                                    Console.WriteLine(Fre(1))
                            GoTo Menu
                            End Select
                        Catch ex As Exception
                            Console.WriteLine("Invalid input")
                        End Try

Solution

  • You need a boolean variable to control the exit from a while loop that encloses your code.

    While the boolean variable is true you continue your loop reading the user input, processing it and reprinting the menu choices. Setting the boolean variable to false will terminate the loop.
    Don't forget to offer an option to terminate the program

    Dim runLoop = true
    while runLoop
      Console.WriteLine("----------------------") 
      Console.WriteLine("1 = option1")
      Console.WriteLine("2 = option2")
      Console.WriteLine("3 = EXIT")
      Console.WriteLine("----------------------")
      Console.Write("Select an option: ")
      opts = Console.ReadLine 
      Console.WriteLine("----------------------")
      Select Case opts
          Case "1"
            Try 
               Console.Write("Enter a word: ")
               word = Console.ReadLine 
               Select Case word.ToLower  
                   Case Eng(0)
                       Console.WriteLine(Fre(0))
                   Case Eng(1)
                        Console.WriteLine(Fre(1))
                        runLoop = false
               End Select
           Catch ex As Exception
                Console.WriteLine("Invalid input")
           End Try           
          case "2"
               .....
          case "3"
               runLoop = false
        End Select
     End While