我正在尝试为某些矩阵运算实现关联运算符,并且还必须使用复数。运行程序后,我遇到以下错误:java.lang.ArrayStoreException:java.lang.Double,我发现此错误是因为instanceof检查在应为true时传递为false。

这是我的代码:

public void readFromFile(int noOfLines, int noOfColumns,T[][] matrix,T t) throws FileNotFoundException
{
    File file = new File("matrix.txt");
    Scanner s = new Scanner(file);
    for (int i = 0; i < noOfLines; ++i)
    {
        for (int j = 0; j < noOfColumns; ++j)
        {
            if(t instanceof ComplexNumber)
                matrix[i][j] = (T)new ComplexNumber(s.nextInt(), 1);
            else if(t instanceof  Integer)
                matrix[i][j] = (T)new Integer(s.nextInt());
            else
                matrix[i][j] = (T)new Double(s.nextInt());
        }
    }
}


问题出现在这一行

if(t instanceof ComplexNumber)
   matrix[i][j] = (T)new ComplexNumber(s.nextInt(), 1);


和这一行的错误

matrix[i][j] = (T)new Double(s.nextInt());


这是我如何调用函数

 ComplexNumber[][] matrix1 = new ComplexNumber[noOfLines][noOfColumns];
 file.readFromFile(noOfLines,noOfColumns,matrix1,ComplexNumber.class);


noOfLines和noOfColumns是整数,readFromFile从文件中读取一些字符串,并将其放在matrix1数组中。
我该如何解决问题,为什么ComplexNumber.class(或我的readFromFile参数中的T t)和instanceOf ComplexNumber不是?谢谢。

编辑:ComplexNumber类

public class ComplexNumber {
public double real;
public double imag;
public String output = "";

public ComplexNumber(double real, double imag) {
    this.real += real;
    this.imag += imag;
}

public ComplexNumber() {
    real = 0;
    imag = 0;
}

public double getReal() {
    return real;
}

public void setReal(double real) {
    this.real = real;
}

public double getImag() {
    return imag;
}

public void setImag(double imag) {
    this.imag = imag;
}

public void add(ComplexNumber num2) {
    this.real += num2.real;
    this.imag += num2.imag;
}

public void subtract(ComplexNumber num) {
    this.real -= num.real;
    this.imag -= num.imag;
}

public void print() {
    System.out.print(real + " " + imag + "i");
}

public String toString() {
    return real + " " + imag + "i";
}
}

最佳答案

您需要Class<T> clazz而不是T t作为参数(或传递new ComplexNumber而不是ComplexNumber.class)。然后,您可以将instanceof替换为clazz.equals(ComplexNumber.class)(对于IntegerDouble相同)。

您传入了Class<ComplexNumber>,而您的else子句将其拾取,因为它不是ComplexNumberInteger,而是Class

07-28 12:50