gpt4 book ai didi

Java:类不被识别为自身的实例

转载 作者:行者123 更新时间:2023-12-02 02:31:16 25 4
gpt4 key购买 nike

我正在尝试为某些矩阵运算实现关联运算符,并且我还必须使用复数。运行程序后遇到以下错误: java.lang.ArrayStoreException: java.lang.Double ,我发现此错误是因为 instanceof 检查传递为 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 )。然后你可以替换instanceofclazz.equals(ComplexNumber.class) (对于 IntegerDouble 也是如此)。

您正在传递 Class<ComplexNumber>和你的else子句正在拾取它,因为它不是 ComplexNumberInteger ,这是一个Class .

关于Java:类不被识别为自身的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47042791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com