-2

I am making an android game that needs to check a float x value, if the value is 320 it should be reset to 1, and if it is not, it should be increased by 15. This is the code that I am using, but however, it is not working:

if (x == 320) {
    x = 1;
    Parachuter p = new Parachuter(x, y);
    parachuters.add(p);
    Toast.makeText(getContext(), "x=" + x + " y=" + y, 15).show();
}
else {
    x = x + 15;
    Parachuter p = new Parachuter(x, y);
    parachuters.add(p);
    Toast.makeText(getContext(), "x=" + x + " y=" + y, 15).show();
}
mskfisher
  • 3,291
  • 4
  • 35
  • 48
user1183066
  • 115
  • 2
  • 6
  • 20

4 Answers4

1

If this is the only code that changes the value of x, then the problem is that x will never be 320. If x starts at 1 and you increment it by 15 each time, then x will eventually become 316, and then 331.

If x starts as 0, then it will become 315 and then 330.

Perhaps changing your if statement to test x >= 320 will do what you want.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
1

Can you tell us what is not working? With floats try and use the F extension to identify its a float (for example x == 320.0f).

I have a feeling you want to know if the X position is greater than or equal to 320, in which case you need to use the following:

            if (x >= 320) {
                x = 1;
                Parachuter p = new Parachuter(x, y);
                parachuters.add(p);
                Toast.makeText(getContext(), "x=" + x + " y=" + y, 15).show();
            }
            else {
                x += 15;
                Parachuter p = new Parachuter(x, y);
                parachuters.add(p);
                Toast.makeText(getContext(), "x=" + x + " y=" + y, 15).show();
            }

Also, I would advise you print out to the Logs rather than creating Toasts every time.

Mimminito
  • 2,803
  • 3
  • 21
  • 27
  • Thanks, i'll try that. But i want to know if x is less than or equal to 320. Thanks for the tips for the toasts:-) It doesn't react when the value is equal and above 320, it just keeps on going without resetting to 1 – user1183066 Mar 19 '12 at 15:23
  • More than likely, the 'x' value is never 320 because of the increment you are using :) If you divide 320 by 15, you get a remainder, which means you will never hit that condition. Also, if 320 is supposed to be your screen width, remember that not all phones are of the same size! – Mimminito Mar 19 '12 at 15:28
1

Do not compare floating point values in this way. Instead of x == 320.0, they should be compared like this:

if (Math.abs(x - 320.0) < EPS) {}

where EPS is a small value like 1e-6 or something small like that.

taskinoor
  • 45,586
  • 12
  • 116
  • 142
0

Use debugger and check what is the value of each variable at a time. It may help to find out the which value assigned to a variable is not working in a correct way.