【问题标题】:pass array to a class as an argument将数组作为参数传递给类
【发布时间】:2020-03-06 18:58:26
【问题描述】:

我正在尝试将数组作为参数传递给另一个类,但不断收到错误消息 “错误:不兼容的类型:Point 无法转换为 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];

【问题讨论】:

    标签: java arrays class arguments


    【解决方案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】:

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

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

      通过更改新 Point 变量的名称来解决此问题。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-12-11
          • 1970-01-01
          • 2012-12-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多