gpt4 book ai didi

java - 构造函数设置/获取。如何设置不返回小于0的值?

转载 作者:行者123 更新时间:2023-12-01 14:47:57 27 4
gpt4 key购买 nike

为每个实例变量提供一个set和一个get方法。如果月薪非正数,则不要设置其值。

我遇到的问题是“未设置值”这是我的代码:

Main.class

public class Main {

public static void main(String[] args) {

Employee myEmp = new Employee("William", "Russell", 30000);
Employee myEmp2 = new Employee("Yevgeniya", "Pakhom", -1);
myEmp.displayMessage();
myEmp2.displayMessage();
}
}

Employee.class


public class Employee {

private String fName;
private String lName;
private double ySalary;

public Employee (String firstName, String lastName, double yearSalary)
{
fName = firstName;
lName = lastName;
ySalary = yearSalary;
}
// Set First Name
public void setFName (String firstName)
{
fName = firstName;
}
// Get First Name
public String getFName()
{
return fName;
}

// Set Last Name
public void setLName (String lastName)
{
lName = lastName;
}
// Get Last Name
public String getLName()
{
return lName;
}

// Set Salary
public void setSalary (double yearSalary)
{

ySalary = yearSalary;

}
// Get Salary
public double getYearSalary()
{

return ySalary;

}
// Display method
public void displayMessage()
{
if (ySalary < 0)
System.out.printf("Hello %s %s, \nI see you're currently making: %.2f\n", getFName(), getLName(),getYearSalary() );


}
}

我在 displayMessage() 方法中放置了一条 if 语句。但我想这并不是“将其设置为空”。

我的妻子也有类似的问题,她将其设置在“获取”下,但我的却没有以同样的方式工作。

最佳答案

将 setSalary 更改为

public void setSalary (double yearSalary)
{
if (yearSalary <= 0) {
throw new IllegalArgumentException("yearSalary: " + yearSalary);
}
ySalary = yearSalary;
}

关于java - 构造函数设置/获取。如何设置不返回小于0的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15217741/

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