Home > Software design >  How to make conditions with IF statement right?
How to make conditions with IF statement right?

Time:12-15

I have question about my IF statement, it just doesn't work :D 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();
    }  
}

CodePudding user response:

Here one error:

    public void SetAge(int age)
    {
        if (_age == 0)  //<-- This should be age==0, not _age
            _age = 21;
        else
            _age = age;
    }

You could benefit from using properties.

CodePudding user response:

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);

CodePudding user response:

Try using the setters you codded when updating the variable, so that it gets to the conditional statements in your code. also, the if statement for age should be :if(age <= 0) _age = 21;

  • Related