简体   繁体   English

如何在Java的setter方法中执行计算?

[英]How do i perform a calculation within a setter method in java?

I have two classes within a java project, one is the Employee1 class and the other is the info class. 我在Java项目中有两个类,一个是Employee1类,另一个是info类。 Within the Employee 1 class I have this code: 在Employee 1类中,我有以下代码:

public class Employee1 {
    String employeeName;
    int hoursWorked;
    double rateOfPay;
    double wages;




public Employee1(String name, int hours, double pay) {
    employeeName=name;
    hoursWorked=hours;
    rateOfPay=pay;

}


public String getName() {
    return employeeName;
}

public void setName(String xName) {
    employeeName = xName;
}


public double getHours() {
    return hoursWorked;
}


public void setHours(int xHours) {
    hoursWorked = xHours;
}


public double getPay() {
    return rateOfPay;
}


public void setPay(double xPay) {
    rateOfPay = xPay;
}

public double calculateWages  () {
wages= hoursWorked * rateOfPay; 
return wages;
} 

public void print() {

    System.out.println("name:"+ employeeName);
    System.out.println("hours " + hoursWorked);
    System.out.println("Wages Earned"+  wages);
}
}

Within my info class I have this code: 在我的信息类中,我有以下代码:

public class Info {

    public static void main(String[] args) {
        Employee1 x= new Employee1("Sarah",40,7.25);
        Employee1 y=new Employee1("Bob",30,8.00);
        Employee1 z= new Employee1("Todd",26, 8.25);



x.print();  


    }

}       

My problem right now is that I am attempting to create a calculation for wages within my Employee1 class as you can see with my calculateWages method. 我现在的问题是,我正在尝试为Employee1类中的工资创建一个计算,就像您通过calculateWages方法可以看到的那样。 However, whenever I call my print method for my existing employee x the wages always come out to be 0.0 and I am unsure why this is happening. 但是,每当我调用现有员工的打印方法x时,工资总是显示为0.0,而且我不确定为什么会这样。 I have preexisting variables for each of my Employee1 objects and I am still getting a 0.0 value for all of their wages but the rest of their information is printed correctly. 我为每个Employee1对象都有一个预先存在的变量,但我仍然获得所有工资的0.0值,但其余信息正确打印。 Can anyone help me with this issue? 谁能帮我解决这个问题? Thank you! 谢谢!

In the code you provide there is not a setter method, instead there is a getter one. 您提供的代码中没有setter方法,而是有一个getter方法。 And yes, you can made calculation in both, getter and setter. 是的,您可以使用getter和setter进行计算。

public void setAmount(int amount){
  this.amount = quantity * price;  
} 

public void getAmount(){
  return this.amount + otherProperty;  
} 

Lets start with this: 让我们以此开始:

I'm new to programming but I know that this type of method is known as a setter. 我是编程的新手,但是我知道这种方法被称为setter。

No it isn't. 不,不是。

In OO, the code (mostly) consists of classes which consist of state (fields) and methods that (typically) operate on that state. 在OO中,代码(大部分)由类组成,这些类由状态(字段)和(通常)对该状态进行操作的方法组成。

By convention ... 按照惯例 ...

  • A setter is a method that sets a field to a new value provided as a method argument. 设置器是一种将字段设置为作为方法参数提供的新值的方法。
  • A getter is a method that returns the value of a field. getter是一种返回字段值的方法。

Your method is neither a setter or a (pure) getter: 您的方法既不是setter也不是(纯)getter:

  • It is not a setter because it doesn't set wages to a supplied value. 它不是设置器,因为它不会将wages设置为提供的值。 (It is doing the calculation based on previously supplied values.) (它基于先前提供的值进行计算。)

  • You could view it as a getter for the wages field, but it is "impure" in that it updates the field as well as returning its value. 您可以将其视为“ wages字段的获取者,但它“不纯净”,因为它会更新该字段并返回其值。


Every time I go to print out the "wages" variable it just gives me a zero and nothing else, I have the other variables hoursWorked & rateOfPay defined in the main 每次我打印“ wages”变量时,它只会给我零,除此之外,我在主变量中定义了其他变量hoursWorked&rateOfPay

We cannot explain this without seeing the rest of your code. 如果不看其余的代码,我们将无法解释。 However, I suspect that the problem is one of the following: 但是,我怀疑问题是以下之一:

  1. Either of hoursWorked or rateOfPay is zero ... because they are not being correctly set / initialized to non-zero values. hoursWorkedrateOfPay均为零...,因为它们未正确设置/初始化为非零值。

  2. The calculateWages method is not being called. 没有调用calculateWages方法。

  3. You have multiple instances of the class that defined this method ... and your code is looking at the wrong one. 您有定义该方法的类的多个实例...并且您的代码正在寻找错误的实例。

  4. Possibly ... some of the variables involved have been incorrectly declared as static .s 可能...某些涉及的变量被错误地声明为static .s


UPDATE - Now that I see your code, the reason that wages is zero is that your code doesn't call calculateWages . 更新 -现在我看到了您的代码, wages为零的原因是您的代码未调用calculateWages

In the best practice of OOP your method should have two arguments: eg 在OOP的最佳实践中,您的方法应有两个参数:例如

public class Answer1 {

    public static double calculateWages  (int hoursWorked, double rateOfPay){
        return hoursWorked * rateOfPay;
    }

    public static void main(String[] args) {

        System.out.println(calculateWages(6, 5.24));

    }

}

You can pass those values to the calculateWages () method. 您可以将这些值传递给calculateWages()方法。 Try this 尝试这个

public double calculateWages  (int hoursWorked, double rateOfPay) {
     return hoursWorked * rateOfPay;
}

You may want to simplify this by creating a class, outside of the main class with the main method, that does this ONE specific job of calculating a wage. 您可能想通过在main类之外使用main方法创建一个类来简化此工作,以完成工资的这一特定工作。 We call this "isolation" in programming, and we want to isolate one class from another and make sure each class only does one particular job. 我们在编程中将此称为“隔离”,我们想将一个类与另一个类隔离,并确保每个类仅执行一项特定的工作。 Here is an example of a class that will get the total wage: 这是一个将获得总工资的类的示例:

public class WagesCalc {

      public static double calculateWages(int hoursWorked, double hourlyWage) {
            double wage = (double)hoursWorked * hourlyWage;
            return wage;
            }

}

In the code above we can create a class that calculates the wages called WagesCalc. 在上面的代码中,我们可以创建一个称为WagesCalc的类来计算工资。 Within it, we can create a method called calculate wages. 在其中,我们可以创建一种称为计算工资的方法。 You can add hours worked, and the hourly wage as the arguments for the class. 您可以添加工作时间和小时工资作为课程的参数。 We then add a variable, and then return an the wage. 然后,我们添加一个变量,然后返回工资。 We make this method static so that we can return it without an instance of the class being created. 我们将此方法设为静态,以便可以在不创建类实例的情况下将其返回。 Here is the code in the main method: 这是main方法中的代码:

public class App { 公共类应用{

       public static void main( String[] args )throws IOException{

            double wages = WagesCalc.calculateWages(23, 23.50);
            System.out.println("My total wage is $" + wages);


      }
}

And here is the output: 这是输出:

My total wage is $540.5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将Double值从一个ActionListener方法引入另一个方法来执行计算? Java的 - How do I bring in Double values from one ActionListener method into another to perform a calculation? Java 如何使用 Stream 并行 Java 执行矩阵计算? - How Do I Perform Matrix Calculation With Stream Parallel Java? Java,如何从一个数字中删除一位数字(以便对其余数字进行计算)? - Java, How do I drop one single digit from a number (In order to perform a calculation on the rest of the number)? 在使用Java时,如何将Scala设置方法'myvar_ $ eq(myval)'别名为更令人愉悦的名称? - How do I alias the scala setter method 'myvar_$eq(myval)' to something more pleasing when in java? java - 如何在java中的setter方法中检查对象空值检查? - How do I check object null checking inside setter method in java? 如何用 java 计算分数? - how can i do the calculation of score with java? 我们可以在java中使用Setter方法来执行操作吗? - Can we use Setter Method in java to perform operations? 如何在方法-Java中更改布尔值? - How do I change the value of a boolean within a method - Java? Java - 如何在 switch 语句中调用方法? - Java - How do I call a method within a switch statement? 如何将数组中的字符串验证为 java 中的方法 - How do I validate string within an array to a method in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM