Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make conditions with IF statement right?

I have question about my IF statement, it just doesn’t work 😀
I want to check ID, age and salary, if it’s bigger than 0, but my code just ignore that, would like to change 0 to some meanings like – if age <= 0 set age = 21 etc
Will glad to see your answers.
Thank you!

class Person
{
    private int _age;
    private string _firstName;
    private string _lastName;
    private int _id;

    public Person(int age, string firstName, string lastName, int id)
    {
        _age = age;
        _firstName = firstName;
        _lastName = lastName;
        _id = id;
    }    
    
    public int GetAge()
    {
        return _age;
    }
    public void SetAge(int age)
    {
        if (_age == 0)
            _age = 21;
        else
            _age = age;
    }
    public int GetId()
    {
        return _id;
    }
    public void SetId(int id)
    {
        if (id > 0)
            _id = id;
        else
            _id = 1;
        
    }
    public void Print()
    {
        Console.WriteLine("Age: {0}\tFirst name: {1}\tLast name: {2}\tID: {3}", this._age, this._firstName, this._lastName, this._id);
    }
}

class TestInheritence
{
    public static void Main(string[] args)
    {
        Employe[] employees = new[]
        {
            new Employe(21, "John", "Watson", 0)
        };
        employees[0].Print();
    }  
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It is because you don’t use the setters which have the if statements, you set the variables directly.
So instead of

_age = age;

You should use

setAge(age);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading