How do i convert goto loops into other loops that are best according to the code

Viewed 39

i have multiple goto loops and i want to convert this into a for loop or a do while loop which ever is better

I was trying to convert but didn't understand how do I convert so many goto statements

also please explain a little how did u done it

 Start: // i used label but i want to use for loop here but i dont know how so i used label temporarily
        Console.WriteLine("Please enetr any gener number: 1- Action,2- Comedy,3- Drama,4- Fantasy,5- Horror,6- Mystery,7- Romance,8- Thriller "); // here user will select a category
        string category = Console.ReadLine();

        if (string.IsNullOrEmpty(category))
        {
            Console.WriteLine("Please enter a number");
            Console.WriteLine();
            goto Start;
        }
        else
        {
            category_no = int.Parse(category);
            if (category_no >= 1 && category_no <= 8)
            {
            imdb:
                Console.WriteLine("please enter a desired imdb rating between 1.0 to 10 (please note you can add . too : )");
                string rating = Console.ReadLine();
                if (string.IsNullOrEmpty(rating))
                {
                    Console.WriteLine("Please enter a rating");
                    Console.WriteLine();
                    goto imdb;
                }
                else
                {
                    imdb = float.Parse(rating);
                    if (imdb >= 1.0 && imdb < 10.0)
                    {
                        Random random = new Random();
                        Program.MovieList();
                        float random1 = random.Next(movie_name.Length);
                        string name = movie_name[(int)random1].ToString();
                        Console.WriteLine(name);

                        // i know this is wrong, but i dont know how can  i call , as of now u probably know what i want to show here
                    }
                    else
                    {
                        Console.WriteLine("Please enter coreect imdb");
                        goto imdb;
                    }
                }
               
            }
            else
            {
                Console.WriteLine("PLease enter a vaild choice");
                Console.WriteLine();
                goto Start;
            }
        }
1 Answers

You can restructure the code into the following methods:

var category_no = GetValidCategoryFromUser();
var rating = GetValidRatingFromUser();
ChooseMovie(category_no, rating);

The first two of these methods can then each contain a while(true) loop, where you return to exit the loop when you have received a valid value.

Related