How do you update an instance variable within an if block?

Phin :

I'm writing code for a course that requires the user to enter data regarding an employee. There are multiple employee types requested in my assignment, one being a salaried employee that can get an optional bonus which adds 10% to their salary.

My issue is that the salary for the employee is not updating as intended within the if block I created. As an aside, the reason I created an instance variable for the bonus was because, as a specification of my course assignment, the bonus should be removable at any point.

Below are the constructors for the Employee superclass, and the Salaried subclass, along with the setter used for the instance variable 'pay'

public static class Employee{
    double pay;


    public void setPay(double p){
            pay = p;
    }

    public double getPay(){
            return pay;
    }

    public Employee(){
    }    
}

public static class Salaried extends Employee{
    private boolean bonus;

    public void setBonus(boolean b){
        bonus = b;
    }

    public Salaried(){
        super();
        System.out.println("What is this employees salary?");
        Scanner sc1 = new Scanner(System.in);
        double p = sc1.nextDouble();
        System.out.println("Give this employee a bonus? Y/N");
        if (sc1.nextLine().equalsIgnoreCase("Y")){
            setBonus(true);
        }
        else if (sc1.nextLine().equalsIgnoreCase("N")){
            setBonus(false);
        }
        if (bonus){
            setPay(p * 1.1);
        }
        else{
            setPay(p);
        }
}

Upon creating a salaried employee and entering, for example, 10000 for the salary and answering 'Y' to the question regarding the bonus, I expect to get 11000 when I try to retrieve the pay instance variable with the getter, but instead get 10000, as if the bonus was never applied. I don't understand why this happens.

Elliott Frisch :

Every time you call sc1.nextLine() it consumes a line, and you call it twice in setting bonus (and the first time, the "Y" is skipped because sc1.nextDouble() leaves a trailing new line). Anyway, you don't need if / else checks to update a boolean field. Something like,

public Salaried() {
    super();
    System.out.println("What is this employees salary?");
    Scanner sc1 = new Scanner(System.in);
    double p = sc1.nextDouble();
    sc1.nextLine(); // <-- consume trailing new line.
    System.out.println("Give this employee a bonus? Y/N");
    bonus = sc1.nextLine().equalsIgnoreCase("Y"); // <-- just set bonus.
    if (bonus) {
        setPay(p * 1.1);
    } else {
        setPay(p);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=133846&siteId=1