0

Good day everyone. To my shame dont understand how to make it. I have a class like:

public class Worker
{
    public int ID { get; set; }
}

And Data class with workers List. Have a method to work with it:

public Department GetWorkerByID (int id)
    {
        foreach (Worker worker in Workers)
        {
            if (worker.ID == id)
                return worker;
        }
        return null;
    {

The problem is i need to give the user ability to choose the current worker from list by its ID number and i want program to handle invalid input like random simbols, letters etc and check if the input ID is exist. Usually i use boolean property for this:

string input = Console.ReadLine();
bool isInt = int.TryParse(input, out _);

And so on. But in case with class properties it doesnt work like i expected and when i try to do this:

while (!isInt && Data.GetWorkerByID(int.Parse(input)) == null)
        {
            Console.Write("Wrong input. Try again: ");
            input = Console.ReadLine();               
        }

Its not working, throwing me the exceptions of invalid format for ID number or pass the number but than trying to get the non existing instance of worker. Any advice welcome.

3
  • Try swapping !isInt && to !isInt || Commented May 27, 2021 at 13:01
  • 1
    The loop doesn't make sense. You want to exit if isInt is true and GetWorkerByID is set but you don't modify these variables in the loop. So you either don't enter it or never exit. Commented May 27, 2021 at 13:02
  • @DekuDesu i tryed but than it start ignore the existing IDs. So for example if i have worker with ID=1 and input 1 its throw message to try again. Commented May 27, 2021 at 13:14

1 Answer 1

1

Try do something like that:

C#:

public Worker TryGetWorker()
{
    string input = Console.ReadLine();
    int index = -1;
    bool isInt = int.TryParse(input,out index);
    Worker worker = Data.GetWorkerByID(index);
    if (!isInt || worker == null)
    {
        Console.Write("Wrong input. Try again: ");
        return TryGetWorker();
    }
    else
        return worker;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Your input is string property, but ID is int and method GetWorkerByID takes int. So its doesnt seems to work.
Sorry, didn't notice, i'l fix that.
Thats hepls, thank you. Just changed if statement to while loop and its working like i need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.