2015-10-02 88 views
-1

我有一個主要的java文件和一個僱員類。對於員工類,我有3個方法 - 一個返回員工姓名的getName方法,一個返回工資的getSalary方法和一個將薪水提高一定百分比的raiseSalary。類構造函數沒有正確初始化值

在我的Main.java文件,我做了一個構造函數初始化該Employee類的值,當我試圖打印輸出這些值,我得到空和0

/** 
* This class tests the Employee object. 
* 
*/ 
public class Main { 

/** 
* Create an employee and test that the proper name has been created. Test 
* the initial salary amount and then give the employee a raise. Then check 
* to make sure the salary matches the raised salary. 
* 

public static void main(String[] args) { 
    Employee harry = new Employee("Hi", 1000.00); 
    System.out.println("Employee name:" + harry.getName()); 
    System.out.println("Salaray: "+ harry.getSalary()); 

    harry.raiseSalary(10); // Harry gets a 10% raise. 
} 

}

/** *這個班級實行一個僱員,這個人是一個有姓名和工資的人。 * */ 公共類Employee {

private String employeeName; 
private double currentSalary; 

public Employee(String employeeName, double currentSalary) { 

} 

// Accessors that are obvious and have no side effects don't have to have 
// any documentation unless you are creating a library to be used by other 
// people. 
public String getName() { 

    return employeeName; 

} 

public double getSalary() { 

    return currentSalary; 

} 

/** 
* Raise the salary by the amount specified by the explicit argument. 
* 
*/ 
public void raiseSalary(double byPercent) { 

    currentSalary = getSalary() * byPercent; 

} 

}

+1

對於e,在這裏發佈您的代碼,而不是在外部資源中。 –

+3

對於兩個,你的構造函數是空的,你爲什麼認爲你的變量會被初始化爲'null'和'0'以外的任何東西? –

回答

0

在構造函數中的參數沒有指向創建外側它的範圍...修復只需

public Employee(String employeeName, double currentSalary) { 
this.employeeName = employeeName; 
this.currentSalary = currentSalary; 

} 
相同的對象

在變量名稱之前添加「this」只需告訴代碼指向範圍外的變量

+0

指向範圍外的變量 - 不正確。這是對當前類的實例的引用。所以this.variableName會引用類實例變量:variableName。 – NormR

相關問題