好的,所以我制作了一个简单的程序来在Java中练习多类,但我不愿意找到此问题的解决方案:

我有2个int[][]变量(坐标),coords1coords2,它们都等于一个要求输入坐标的函数,

奇怪的是,在第一个输入之后,coords1获取了它的值,然后我输入了coords2,它也得到了它的值,但是同时coords1将自动获得与coords2相同的值不知道为什么,这是代码:

if(simbolo.equals("circulo") || simbolo.equals("Circulo") || simbolo.equals("Circle") || simbolo.equals("circle")){
            circulo.setColour();
            colour1 = circulo.getColour();
            circulo.setColour(); //circulo 2
            colour2 = circulo.getColour();
            coords1 = circulo.getCoords();                                         //IMPORTANT PART
            System.out.println("coords1: " + coords1[0][0] + " " + coords1[0][1]);//IMPORTANT PART
            coords2 = circulo.getCoords();//circulo2                              //IMPORTANT PART
            //System.out.println("coords2: " + coords2[0][0] + " " + coords2[0][1]);
            System.out.println("2-coords1: " + coords1[0][0] + " " + coords1[0][1]);//IMPORTANT PART
            circulo.setRaio();
            r1 = circulo.getRario();
            circulo.setRaio(); //circulo2
            r2 = circulo.getRario();
            area1 = calcCircleArea(r1);
            perimetro1 = calcCirclePerimeter(r2);
            area2 = calcCircleArea(r1);//circulo2
            perimetro2 = calcCirclePerimeter(r2);
            distance = Distance(coords1, coords2);
            System.out.println("A distância entre os centros dos círculos é: " + distance);
            intersection = Intersects(distance, r1, r2);
            System.out.println(intersection);
        }


第一个System.out.println("coords1: " + coords1[0][0] + " " + coords1[0][1]);将为我提供与System.out.println("2-coords1: " + coords1[0][0] + " " + coords1[0][1]);不同的值

这是功能setCoordinates()

public int[][] center = new int[1][2];

    Scanner scan = new Scanner(System.in);

    public int[][] setCoordinates(){
    System.out.println("Introduza a coordenada do centro: x ");
    center[0][0] = scan.nextInt();
    System.out.println("y: ");
    center[0][1] = scan.nextInt();

    System.out.println("Centro atual: " + Arrays.toString(center[0]));
    return center;
    }


circulo getCoords()中的函数仅从该函数中获取返回值。

编辑:"IMPORTANT PART"是我使用这些变量的地方

肯定有些事情我做不正确,但是在哪里?

谢谢

最佳答案

由于您在setCoordinates方法之外声明了变量中心,因此它不是该方法的局部变量。这就是为什么每次调用setCoordinates方法时,以前的值都会被新值覆盖的原因。您需要在setCoordinates方法内声明变量中心。

08-28 13:21