作业:错误:方法声明无效;需要返回类型

时间:2016-11-08 03:19:24

标签: java oop constructor

我正在尝试通过将数组作为输入(以及其他内容)来创建一个将创建矩阵的类。此数组将分配给记录(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有关。

2 个答案:

答案 0 :(得分:0)

嗯,我注意到的事情很少。编辑:如下所述,构造函数名称必须与类名相同。

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

答案 1 :(得分:0)

我的想法是你想在公共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;
}    

}