سؤال

First of all, I have this interface:

public interface GeometricFigureInterface extends Comparable {

double getArea();

TreeSet<?> getByText(String text);

@Override
public int compareTo(Object o);

}

And then a Rectangle

public class Dreptunghi implements GeometricFigureInterface {

private double x1;
private double y1;
private double x2;
private double y2;

public Dreptunghi() {
    super();
}

public Dreptunghi(double x1, double y1, double x2, double y2) {
    super();
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
}

@Override
public double getArea() {
    return Math.sqrt(Math.pow(x1 - y2, 2) + Math.pow(x2 - y2, 2));
}

And i have a method that reads from a text the coordonates

@Override
public TreeSet<Dreptunghi> getByText(String text) {
    String file ="D:/FiguriGeometrice.txt"; 
    BufferedReader br = null;
    TreeSet<Dreptunghi> setDreptunghiuri = new TreeSet<Dreptunghi>();
    Dreptunghi d = new Dreptunghi();
    try {

        String line = "";
        FileReader fr = new FileReader(file);
        br = new BufferedReader(fr);

        while ((line = br.readLine()) != null) {

            String[] s = line.split(" ");
            if (s[0].equals("D")) {
                d.setX1(Double.parseDouble(s[1]));
                d.setY1(Double.parseDouble(s[2]));
                d.setX2(Double.parseDouble(s[3]));
                d.setY2(Double.parseDouble(s[4]));

//HERE is my problem when I add this the
compareToMethod is called but the objects are the same and i end up with only one object regardless of the values

                setDreptunghiuri.add(d);

            }

        }
    } catch (Exception e) {
        ....

    }
    return setDreptunghiuri;
}

@Override
public int compareTo(Object o) {
    Dreptunghi d = (Dreptunghi)o;
    if(this.getX1() == d.getX1())
        return 0;
    return 1;
}
هل كانت مفيدة؟

المحلول

Define the class inside the loop or only initialise it inside condition

if (s[0].equals("D")) {
            Dreptunghi d = new Dreptunghi();
            d.setX1(Double.parseDouble(s[1]));
            d.setY1(Double.parseDouble(s[2]));
            d.setX2(Double.parseDouble(s[3]));
            d.setY2(Double.parseDouble(s[4]));

            setDreptunghiuri.add(d);

        }

or

 if (s[0].equals("D")) {
                d = new Dreptunghi();
                d.setX1(Double.parseDouble(s[1]));
                d.setY1(Double.parseDouble(s[2]));
                d.setX2(Double.parseDouble(s[3]));
                d.setY2(Double.parseDouble(s[4]));

                setDreptunghiuri.add(d);

            }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top