I got a problem with my code. As I try to compare two variables with different values by calling isEqual() method. But it gave me a result of true. Can someone spot the problem? My FloatingPoint Class
import io.*;
//Class FloatingPoint
public class FloatingPoint
{
//Constant
public static final double MINPRECISION = 0.00000001;
//Variable
private static double precision;
//Default constructor
public FloatingPoint()
{
precision = MINPRECISION;
}
//Unsure if need a alternatve
//Alternative constructor
public FloatingPoint(double value)
{
if( (value < 0.0) || (value > 1.0) )
{
throw new IllegalArgumentException("Invalid reliability!");
}
setPrecision(value);
}
//Copy Constructor
public FloatingPoint(FloatingPoint num)
{
precision = num.getPrecision();
}
//getPrecision
public double getPrecision()
{
return precision;
}
//isEqual
public boolean isEqual(FloatingPoint num)
{
return (Math.abs(precision - num.getPrecision()) < MINPRECISION);
}
//setPrecision
public static void setPrecision(double value)
{
precision = value;
}
}
And this is my Main Class
import java.io.*;
public class TestFloatingPoint
{
public static void main(String [] args)
{
FloatingPoint f1, f2;
f1= new FloatingPoint(0.2);
System.out.print(f1.toString());
f2=new FloatingPoint(1.0);
System.out.print(f2.toString());
System.out.print(f1.toString());
System.out.print(f1.isEqual(f2));
System.exit(0);
}
}
As I try to compare two variables with different values by calling isEqual() method.
You don't have variables with different values, because you only have one value - a static variable:
private static double precision;
(Change the declaration of setPrecision
to not be static too.)
Declaring that as static
means it's associated with the type rather than with any instance of your type. Your class doesn't declare any instance fields, and therefore doesn't have any state (other than object identity).
The simple fix is to make it an instance field:
private double precision;
But you should read up more on what static
means so you can decide when to use it and when not to use it in the future. See the Java tutorial as a starting point.
See more on this question at Stackoverflow