我正在尝试为一些矩阵运算实现一个关联运算符,而且我还必须使用复数。我在运行程序后遇到以下错误:java.lang.arraystoreexception:java.lang.double,我发现这个错误是因为instanceof check传递为false,而它应该是true。
这是我的密码:
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);
noofline和noofcolumns是整数,readfromfile从文件中读取一些字符串,它应该将它们放入matrix1数组中。如何解决这个问题,为什么complexnumber.class(或readfromfile参数中的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";
}
}
1条答案
按热度按时间xam8gpfp1#
你需要
Class<T> clazz
而不是T t
作为参数(或传入new ComplexNumber
而不是ComplexNumber.class
). 然后你可以替换instanceof
与clazz.equals(ComplexNumber.class)
(和Integer
以及Double
).你要过去了
Class<ComplexNumber>
还有你的else
因为它不是一个ComplexNumber
或者一个Integer
,这是一个Class
.