mercredi 5 septembre 2018

Is there other way to write this if code?

I just started to learn c#, i am most comfortable with if and if else. Right now am working on a program where it writes a ip adress and i need to type the correct subnet, and all that. It takes to long time to make the code with if and else if, so i was wondering if there is a faster way to do it.

Random r = new Random();
            int randomip = r.Next(256);
            int secondip = r.Next(256);
            int subnetip = r.Next(24, 31);
            int numbers = subnetip;

Console.WriteLine("192.168." + randomip + "." + secondip + "/" + subnetip);

            Console.Write("Type the correct netID: ");
            Console.ReadLine();
            Console.Write("Type the correct subnet: ");
            Console.ReadLine();


            if (numbers == 24)
            {
                Console.WriteLine("correct netID is: 192.168." + randomip + 
                "." + secondip / 256);
                Console.WriteLine("correct subnet is: 255.255.255.0");
            } else if (numbers == 25)
            {
                Console.WriteLine("correct netID is: 192.168." + randomip + 
                "." + secondip / 128);
                Console.WriteLine("correct subnet is: 255.255.255.128");
            } else if (numbers == 26)

and so on… with other numbers isn’t there a faster and easier way to make it? It works but if i want to add more numbers there would be a problem

Aucun commentaire:

Enregistrer un commentaire