mercredi 29 avril 2020

JAVA ~ if-else block doesnt work as expected [closed]

ok so this time i want to make a program that takes the data of some people (name, salary, sex etc) and shows them on the screen. there are two classes, a Person and its subclass MarriedPerson. Person goes like this:

public class Person
{
    //[...]
    private float salary;
    //[...]
    public static final int MALE=0;
    public static final int FEMALE=1;  
    private int sex;
    //[...]}

MP has a method named setSalary that takes a MarriedPerson variable and return void. the purpose of this is that, if the variable has the different sex from the object, then it returns the objects salary plus the variable's salary, but if the sexes are the same, then nothing happens. kinda home of phobic i know but whatever i just want to pass this class

after struggling with this my prof suggested i try this:

public void setSalary(MarriedPerson spouse)
        {        
          float x;
          if (getSex() != spouse.getSex()) 
          x=this.getSalary()+spouse.getSalary();
        }

however, when i run the program, no matter the sex of the variable, the salary returned is always the same! for example, for these three:

   MarriedPerson mp1 = new MarriedPerson(980.5f, Person.FEMALE);
   MarriedPerson mp2 = new MarriedPerson(2080f, Person.MALE); 
   MarriedPerson mp3 = new MarriedPerson(600f, Person.FEMALE);

   mp1.setSalary(mp2);
   mp1.printInfo();

   mp1.setSalary(mp3);
   mp1.printInfo();

im expecting two messages like:

mp1 has a salary of 3060.5 $ //980.5+2080
mp1 has a salary of 3060.5 $ //both female, so its the same as before

but instead i get this!

mp1 has a salary of 980.5 $ 
mp1 has a salary of 980.5 $

as if nothing happens! why!!

Aucun commentaire:

Enregistrer un commentaire