Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

Thread: Method returning negative numbers seemingly at random

1. Method returning negative numbers seemingly at random

Hi everyone. I'm trying to write a game that involves balls colliding with each other, but I couldn't get them to go in the right directions. Here's what I've narrowed the problem down to:

The colliding balls are b1 and b2. First I gave assigned their velocities to variables:

```double xvel1=b1.xvel();
double xvel2=b2.xvel();
double yvel1=b1.yvel();
double yvel2=b2.yvel();```

As an experiment, I entered the following code:

```System.out.print(b1.xvel()+" "+xvel1);

b1.setXVel(b1.xvel());
b1.setYVel(b1.yvel());
b2.setXVel(b2.xvel());
b2.setYVel(b2.yvel());

System.out.println(b1.xvel()+" ");```

Here are the methods I used above:

```public double xvel() {return xvel;}

public double yvel() {return yvel;}

public void setXVel(double xv1) {xvel=xv1;}

public void setYVel(double xv1) {xvel=xv1;}```

The result of this SHOULD have been that I assigned each ball's velocity to itself.

According to the numbers that were printed, b1.xvel() and xvel1 were the same. But after

b1.setXVel(b1.xvel());
b1.setYVel(b1.yvel());
b2.setXVel(b2.xvel());
b2.setYVel(b2.yvel());

the value of b1.xvel() changed. Sometimes it was a slightly different number. Other times it was negative. When I took those lines away I didn't get this error, so those four lines are causing the problems.

Has anyone had problems like this before? Is there something deeply weird going on, or am I missing something simple?

2. Re: Method returning negative numbers seemingly at random

`public void setYVel(double xv1) {xvel=xv1;}`
Perhaps this is the problem? (notice the xvel instead of yvel)

3. Re: Method returning negative numbers seemingly at random

Not sure if this will fix your problem since you didn't provide full code, but it is an error at least.

```public void setXVel(double xv1) {xvel=xv1;}

public void setYVel(double xv1) {xvel=xv1;}```

This code only lets you set the x velocity (xvel). So the method says you are setting the Y velocity, but it is in fact setting the X velocity.
This could be affecting your calculations later on.

4. Re: Method returning negative numbers seemingly at random

*DEEP SIGH*...
Thank you! I guess that was a copy-paste error. Everything is working perfectly now.