Search code examples
javainteger-division

Setter can't modify the field properly


I am encountering a problem when creating a program to solve simple kinematics.

I run the program and find out the fields haven't been modified properly . Here is the scrap of my program that initialise the object and setting the variables.

public class LinearConstantAcceleration1DKinematics {
    private double distance;
    private double speed;
    private double acceleration;
    private double time;

    public LinearConstantAcceleration1DKinematics() {
        /* initialize the object */
        distance = 0;
        speed = 0;
        acceleration = 0;
        time = 0;

    }

    public void setS(double s) {
        this.distance = s;
    }
    //continue with 3 more setters which is created in the same way ,i have omitted them here

    public double getU(){
    double u_ans;

    u_ans = (distance - 1/2 *acceleration*time*time )/time;
    return u_ans;
    }



}

And here is the main that uses the methods

LinearConstantAcceleration1DKinematics kinematics = new LinearConstantAcceleration1DKinematics();

    kinematics.setS(175);
    kinematics.setA(10);
    kinematics.setT(5);
    System.out.printf(%f\n", kinematics.getU());

The result is 35 which is incorrect.Many thanks for your help.


Solution

  • This has absolutely nothing to do with setter methods -- your division is wrong since 1 / 2 does int division and returns 0 resulting in the equation calculating simply distance / time.

    Change to:

    u_ans = (distance - 1.0 / 2.0 * acceleration * time * time) / time;
    

    Lesson to learn: don't assume where the error is -- test it. Use a debugger or println statements to check the states of your variables as your program runs.