有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将数组作为参数传递给类

我试图将一个数组作为参数传递给另一个类,但不断得到错误 “错误:不兼容的类型:无法将点转换为int[]”

我的代码的第一部分是:

public Circle(int n, int x, int y)
    {
        radius = n;
        counter++;
        center[0] = x;
        center[1] = y;


        Point center = new Point(center);


    }    

Point是需要将数组传递给它的类

代码的第二部分:

public class Point 
{
    private int xCord;
    private int yCord;

    public Point (int [] center)

    {
        xCord = center[0];
        yCord = center[1];


共 (3) 个答案

  1. # 1 楼答案

    你必须在这里考虑对象。这里的变量名是重复的。由于中心对象保留阵列引用,因此不能保留相同的变量来保留点对象

    您可以相应地修改代码。附上你的样本代码

    public class Test {
    
        public static void main(String[] args) {
            Circle(1,2,3);
    
        }
    
        static void Circle(int n, int x, int y)
        {   int center[] = new int[2];
            //Do your operation and initialize the array
            center[0] = 25;
            center[1] = 26;
            Point pointObject = new Point(center);
    
        }   
    
    
    }
    
    
    class Point 
    {
        private int xCord;
        private int yCord;
    
        public Point (int [] center)
    
        {
            xCord = center[0];
            yCord = center[1];
    
        }
    }
    
  2. # 2 楼答案

    这对我来说是不清楚的,但是它显然会导致circle类构造函数中出现错误

    center[0] = x; // center is an int array
    center[1] = y;
    Point center = new Point(center); // ?????
    //     ^^^                ^^^^ Duplicate variable names
    

    通过更改新的Point变量的名称来修复此问题

  3. # 3 楼答案

    Point center = new Point(center);
    重复变量
    更改为
    Point point = new Point(center);