所以,我在这里遇到一个非常奇怪的问题。当我将值user.salary乘以1.1时,由于某种原因它变为0!原来的user.salary变量没问题,我确认它与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);
}
}
答案 0 :(得分:9)
您的构造函数有拼写错误:
Employee (String firstname, String lastname, double Salary){
double salary
应为小写。正如这一行:
this.salary = salary;
没有任何内容,因为它等同于this.salary = this.salary
。
只要将参数更改为小写薪水,它就会将您传递给构造函数的值分配给薪水字段。
答案 1 :(得分:5)
您的构造函数中似乎存在问题:
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)
}
这样salary
未设置,并保留默认值0
。问题的其余部分只是数学。将行更改为此
this.salary = Salary
将解决这个问题,我建议您使用Java的命名约定并命名以小写字母开头的参数,例如newSalary
。