【问题标题】:java : Can't use constructor in array [duplicate]java:不能在数组中使用构造函数[重复]
【发布时间】:2018-10-29 16:20:41
【问题描述】:

我是一名 java 学生,有一个关于如何在数组中创建具有属性的对象的问题。 所以这是我的空构造函数和带有变量的构造函数来设置属性

public class Punt {
    private int x;
    private int y;

    public void Punt(){

    }

    public void Punt(int x, int y){
        this.x = x;
        this.y = y;
    }     
}

然后我需要用 x,y 创建一个创建对象的数组,我得到了这个

public class Punten {
    private int[] punten = {new Punt(3, 4),
        new Punt(5, 12),
        new Punt(7, 24),
        new Punt(9, 40),
        new Punt(11, 60),
        new Punt(13, 84)
};

错误是 Punt 中的 Punt() 不能应用于 (int, int) 红线在两个整数下面

提前感谢您的宝贵时间

【问题讨论】:

  • 从“构造函数”中删除void,否则它们将被视为常规方法。
  • 不是int[],而是Punt[]
  • 应用上述 2 项更改,您应该没问题。

标签: java arrays object constructor attributes


【解决方案1】:
  1. 构造函数没有return type,因此请从您的 2 个构造函数中删除 void

    public Punt(){
    }
    public void Punt(int x, int y){
        this.x = x;
        this.y = y;
    } 
    
  2. 您正在实例化一个 Punt 元素数组,而不是整数数组

    private Punt[]
    

【讨论】:

    猜你喜欢
    • 2017-08-16
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 2015-04-27
    • 2015-07-02
    • 2011-03-22
    • 2018-08-02
    相关资源
    最近更新 更多