【问题标题】:Homework: error: invalid method declaration; return type required作业:错误:无效的方法声明;需要返回类型
【发布时间】:2017-03-21 13:48:45
【问题描述】:

我正在尝试创建一个类,该类将通过将数组作为输入(除其他外)来创建矩阵。这个数组将被分配给一个记录(Record9)。但是,在尝试编译时出现此错误。您可以在下面找到我的代码:

public class Matrix3x3flat {

    private class Record9 {
        public long r1c1;
        public long r1c2;
        public long r1c3;

        public long r2c1;
        public long r2c2;
        public long r2c3;

        public long r3c1;
        public long r3c2;
        public long r3c3;
    }
    private Record9 mat;

    public Record9(long[] arr) {
        Record9 this.mat = new Record9();

        this.mat.r1c1 = arr[0];
        this.mat.r1c2 = arr[1];
        this.mat.r1c3 = arr[2];
        this.mat.r2c1 = arr[3];
        this.mat.r2c2 = arr[4];
        this.mat.r2c3 = arr[5];
        this.mat.r3c1 = arr[6];
        this.mat.r3c2 = arr[7];
        this.mat.r3c3 = arr[8];

        return this.mat;
    }    
}

我不明白这个问题,但我怀疑这与我在 return 语句中没有正确引用 this.mat 有关。

【问题讨论】:

    标签: java oop constructor


    【解决方案1】:

    我的想法是你想在公共 Record9(long[] arr) 上创建 Record9 的实例,目前你在构造函数的 i 侧使用 return 语句,这是不允许的。所以你需要把它转换成一个方法。

    试试这样:

    公共类 Matrix3x3flat {

    private class Record9 {
        public long r1c1;
        public long r1c2;
        public long r1c3;
    
        public long r2c1;
        public long r2c2;
        public long r2c3;
    
        public long r3c1;
        public long r3c2;
        public long r3c3;
    }
    private Record9 mat;
    
    public Record9 instance(long[] arr) {
        this.mat = new Record9();
    
        this.mat.r1c1 = arr[0];
        this.mat.r1c2 = arr[1];
        this.mat.r1c3 = arr[2];
        this.mat.r2c1 = arr[3];
        this.mat.r2c2 = arr[4];
        this.mat.r2c3 = arr[5];
        this.mat.r3c1 = arr[6];
        this.mat.r3c2 = arr[7];
        this.mat.r3c3 = arr[8];
    
        return this.mat;
    }    
    

    }

    【讨论】:

      【解决方案2】:

      嗯,我注意到的几件事。编辑:如下所述,构造函数名称需要与类名称相同。

      2) 为什么要将 mat 声明为 Record9 的一种类型。你已经把它设置为 Record9 的类型了,不需要再定义它,你可以说 this.mat = 不管它需要是什么

      【讨论】:

        猜你喜欢
        • 2019-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多