gpt4 book ai didi

java - 未使用局部变量的值

转载 作者:行者123 更新时间:2023-12-01 16:57:55 26 4
gpt4 key购买 nike

我正在学习 java,在类里面我们开始使用多个类......我有一个带有默认构造函数的员工类。其中我有带有默认值的变量。我遇到的问题是默认构造函数中的变量值没有被使用,所以我在变量下得到黄色下划线。有人可以引导我走向正确的方向吗?

package week2;

import java.text.NumberFormat;

public class Employee {

//Instance Variables
private String firstName = "", lastName = "";
private char gender = 'U';
private int dependents = 0;
private double annualSalary = 0;

//Default Employee Constructor
public Employee() {
String firstName = "not given";
String lastName = "not given";
char gender = 'U';
int dependents = 0;
double annualSalary = 20000;
} //End of default Employee Constructor

//Employee Constructor with variables
public Employee(String firstName, String lastName, char gender, int dependents, double salary) {
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.dependents = dependents;
this.annualSalary = salary;
} //End of Overloaded Employee Constructor

//Calculate Pay
public double annualSalary() {
return (getAnnualSalary() / 52);
} //End Calculate Pay

//Display Employee
public void displayEmployee() {
NumberFormat nf = NumberFormat.getCurrencyInstance();

System.out.println("First Name: \t" + this.firstName);
System.out.println("Last Name: \t" + this.lastName);
System.out.println("Gender: \t" + this.gender);
System.out.println("Dependents: \t" + this.dependents);
System.out.println("Annual Salary: \t" + nf.format(this.annualSalary));

System.out.println("Weekly Pay: \t" + nf.format(annualSalary()));
} //End Display Employee


//Getters and Setters
//Get-Set firstName
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}

//Get-Set lastName
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}

//Get-Set Gender
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}

//Get-Set dependents
public int getDependents() {
return dependents;
}
public void setDependents(int dependents) {
this.dependents = dependents;
}

//Get-Set annualSalary
public double getAnnualSalary() {
return annualSalary;
}
public void setAnnualSalary(double annualSalary) {
this.annualSalary = annualSalary;
}
}

最佳答案

您正在默认构造函数中创建局部变量。删除声明,它将为类级别变量赋值。

//Default Employee Constructor 
public Employee() {
firstName = "not given";
lastName = "not given";
gender = 'U';
dependents = 0;
annualSalary = 20000;
} //End of default Employee Constructor

注意:黄色表示警告。在您的情况下,它暗示您正在创建局部变量并为其赋值,这在您的构造函数中不使用,并且局部变量在构造函数外部不可见。

<小时/>

如果没有使用相同名称定义其他局部变量,则可以使用 this.firstNamefirstName。 (您可以在您的情况下在默认构造函数中使用它们)

如果某个局部变量使用相同的名称定义,则 firstName 引用局部变量,而 this.firstName 引用类级别变量。(您可以在参数化构造函数)

关于java - 未使用局部变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30236100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com