Question

Basic problem but I can't seem to wrap my head around it:

I have something that rotates and I want to stop it at a certain range.

So I want it to return false if the rotation (which is in double) is within a certain range.

Example

Rotation = 182, StopAt 180, Accuracy 2. So should stop.

Rotation = 182, StopAt 180, Accuracy 1. So should not stop.

Current I have:

/**
 *
 * @return
 * number = 100, current = 105, accuracy = 10
 * Example
 * 105c / 100n = 1.05..
 * 10c / 100n = 0.1..
 */
public boolean stopAtRange(double number, double current, double accuracy)
{
    if(current / number) + accuracy)
    {
        return true;
    }
    return false;
}
Était-ce utile?

La solution

In Java if only takes boolean values, and integer values aren't converted to boolean.

To achieve what you want, your method should be like this

public boolean stopAtRange(double number, double current, double accuracy)
{
    if( Math.abs(current - number) <= accuracy)
    {
        return true;
    }
    return false;
}

This work both if current is bigger or smaller than number. If you only want to stop if current is bigger or at least equals to number, than you should remove the Math.abs

I also suggest to use this version:

public static boolean stopAtRange(double number, double current, double accuracy) {
  return Math.abs(current - number) <= accuracy;
}

because it's more compact, and is optimized, for performances as well.

Autres conseils

Your question is a bit confusing, but I'll try my best to help. :)

This code won't compile:

if(current / number) + accuracy)

Firstly, you've opened one bracket and then closed two. You would want:

if((current / number) + accuracy)

Secondly, this won't evaluate to a Boolean value (true or false), which is necessary for your if statement to work. You want:

public boolean stopAtRange(double number, double current, double accuracy)
{
    if(Math.abs(current - number) <= accuracy) return true;
    return false;
}

This works out the difference between your numbers (100 & 105) and confirms if they are within the range (10).

Hope this helps!

Following will stop if current is +/-accuracy away from number:

public boolean stopAtRange(double number, double current, double accuracy)
{
    if( Math.abs(current - number) <= accuracy)
    {
        return true;
    }
    return false;
}

if accepts a boolean value, not a double. Something like:

public boolean stopAtRange(double number, double current, double accuracy)
{
    if(Math.abs(current-number) <= accuracy)
    {
        return true;
    }
    return false;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top