Any other way to write the code

Updated on September 4, 2018 in [A] C# .Net
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
0 on September 4, 2018

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.

Small part of my code:

Random r = new Random();
int randomip = r.Next(256); // the third number not used for anything
int secondip = r.Next(256); // devide and check if i type the real one
int subnetip = r.Next(24, 31); // from 24 to 30 (subnet)
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)
{
Console.WriteLine(“correct netID is: 192.168.” + randomip + “.” + secondip / 64);
Console.WriteLine(“correct subnet is: 255.255.255.192”);
}

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

  • Liked by
Reply