Gonzalo
Gonzalo

Reputation: 160

C# how to create while loop to validate if object is null

I am having issues with two validations working together, one in the Main method and the other one in the Controller Class.

So this is my static method inside the Main. Basically I ask the user to input the ID for an "Employee", the ID is a property of a Class named Employee, and then I show a message saying if that employee exists or not. Let's assume that I have several Employee objects already created. I know it's a form of while loop but I just cant get it right.

My method inside the controller class is correct so there is no need to change anything. Basically it takes the ID and returns null if the Employee object does not exist or returns the object if it does exist. I need to take that null if the employee doesnt exist and create a loop that keeps asking the user to input a correct ID until he does, then the loop ends. Thank you, sorry if I did not explain it correctly.

    public static void mymethod()
    {
        Console.WriteLine("Please enter your Employee ID: ");
        int ID = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("----------------------------");
        Employee employee = controllerclass.findemployee(ID);
        int i = 0;
        bool flag = false;
        while (!flag)
        {
            if (!flag)
            {
                if (ID != null)
                {
                    Console.WriteLine("The employee exists");
                    flag = true;
                }
                else
                {
                    Console.WriteLine("Please enter a valid ID");
                }
            }
            i++;
        }

My method inside the controller class is correct so there is no need to change anything. Basically it takes the ID and returns null if the Employee object does not exist or returns the object if it does exist. I need to take that null if the employee doesnt exist and create a loop that keeps asking the user to input a correct ID until he does, then the loop ends. Thank you, sorry if I did not explain it correctly

Upvotes: 2

Views: 8968

Answers (3)

jimboweb
jimboweb

Reputation: 4542

Use a do-while loop, something like this:

boolean flag = false;
do {
    if(flag)
        Console.WriteLine("Please enter a valid ID");
    else 
        Console.WriteLine("Please enter your Employee ID: ");
    try{
         int ID = Convert.ToInt32(Console.ReadLine());
    } catch (FormatException e){
        Console.WriteLine("Please enter an integer");
        flag = false;
        continue;
    } 
    employee = controllerclass.findemployee(ID);
    flag = true;
} while (employee == null) //employee will be null if not found
Console.WriteLine("The employee exists");

The do while makes sure it happens at least once. The flag conditional will happen after the first entry; if they get it right the first time it'll never happen.

Upvotes: 1

CodingYoshi
CodingYoshi

Reputation: 27009

Whenever you want to do something at least once and possibly more times until a condition has been met (id is found), you should use the do while construct. Here is some code:

int id;
bool idIsNotNumeric = true;
do
{
    Console.WriteLine("Please enter your Employee ID: ");
    string idEntered = Console.ReadLine();
    idIsNotNumeric = !int.TryParse(idEntered, out id);

    // other stuff you want to keep doing

} while (idIsNotNumeric || controllerclass.findemployee(id) == null);

Console.WriteLine("The employee exists");

Upvotes: 2

Scott Hannen
Scott Hannen

Reputation: 29222

One detail is that an int can never be null because it's a value type. You could change it to int? which is a nullable int - it can have a value or be null.

The key to making a `while' loop work is that whatever condition it's checking has to be changed inside the loop.

In this case ID is getting set before the loop starts, and there's nothing inside the loop to ever change it.

You could do something like this. (This is a little more nesting than I usually do, but it works.)

public static void mymethod()
{
    Employee employee = null
    while(employee == null)
    {
        Console.WriteLine("Please enter your Employee ID: ");
        int ID = 0;
        var input = Console.ReadLine();
        if(int.TryParse(input, out ID))
        {
            employee = controllerclass.findemployee(ID);
            if(employee == null)
            {
                Console.WriteLine("The employee does not exist");
            }
            else
            {
                Console.WriteLine("The employee exists");
            }
        }
        else
        {
            Console.WriteLine("Please enter a valid ID.");
        }
    } // Doesn't exit the loop until we have an employee

The loop will execute as long as employee is null. So until they enter something that returns a valid employee, it will keep going.

I used int.TryParse to check the value they entered. It returns true if what they entered is an integer, otherwise false. That way if they entered a valid integer we check for the employee. If it's not even a valid integer then it lets them know.

One way to think of a while loop is just to think of what condition you're trying to meet before you exit the loop. In this case you want employee to be something other than null. So the loop can begin with while(employee==null).

Upvotes: 2

Related Questions