In Java, are two duplicates matching together equal to zero?

So I have a very strange problem. When I multiply the user.salary value by 1.1, it becomes 0 for some reason! The original user.salary variable is ok, I confirmed it should be with System.out.println.

import javax.swing.JOptionPane;


class Employee{
    String firstname;
    String lastname;
    double salary;
    Employee (String firstname, String lastname, double Salary){
        this.firstname = firstname;
        this.lastname = lastname;
        this.salary = salary;
    }

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getLastname() {
    return lastname;
}

public void setLastname(String lastname) {
    this.lastname = lastname;
}

public double getSalary() {
    return salary;
}

public void setSalary(double salary) {
    this.salary = salary;
}



}

 class NameDialog{
 public static void main( String[] args )
 {

String firstname = JOptionPane.showInputDialog("What is your first name?");
String lastname = JOptionPane.showInputDialog("What is your last name?");
String salarystring = JOptionPane.showInputDialog("What is your salary?");
Double salary = Double.parseDouble(salarystring);
Employee user = new Employee (firstname, lastname, salary);
String message = String.format("Hello, %s %s.", user.firstname, user.lastname);
JOptionPane.showMessageDialog(null, message);
double raise = (user.salary)*1.1;

JOptionPane.showMessageDialog(null, "Congratulations, you have received a raise! Your salary is now "+raise);
  } 
}

      

+3


source to share


2 answers


There is a problem in your constructor:

Employee (String firstname, String lastname, double Salary){
    this.firstname = firstname;
    this.lastname = lastname;
    this.salary = salary; //You assign salary to itself, since the 
                          //parameter is Salary (with caps)
}

      

Thus, it is salary

not installed and remains with the default value 0

. The rest of the problem is just math. Changing the line on this



 this.salary = Salary

      

will solve the problem, I highly recommend that you use the Java naming convention and name the parameters lowercase, eg newSalary

.

+5


source


There is a typo in your constructor:

Employee (String firstname, String lastname, double Salary){

      

double salary

must be lowercase. Since this is a line:



this.salary = salary;

      

Doesn't do anything that is equivalent this.salary = this.salary

.

Once you change the parameter to lowercase salary, it will assign the value you pass to the constructor to the salary field.

+9


source







All Articles