I am trying to implement an associative operator for some matrix operations, and I must also use complex numbers. I encounter the following error after I run my program: java.lang.ArrayStoreException: java.lang.Double , and I found out that this error is because an instanceof check passed as false, when it should be true.
Here is my code:
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());
}
}
}
The problem appears at this line
if(t instanceof ComplexNumber)
matrix[i][j] = (T)new ComplexNumber(s.nextInt(), 1);
and the error at this line
matrix[i][j] = (T)new Double(s.nextInt());
Here is how I call the function
ComplexNumber[][] matrix1 = new ComplexNumber[noOfLines][noOfColumns];
file.readFromFile(noOfLines,noOfColumns,matrix1,ComplexNumber.class);
noOfLines and noOfColumns are integers, and readFromFile reads some strings from a file, and it should put them in the matrix1 array. How can I fix the problem, and why isn't ComplexNumber.class (or T t in my readFromFile arguments) and instanceOf ComplexNumber? Thank you.
EDIT: ComplexNumber class
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";
}
}
You need Class<T> clazz
instead of T t
as the parameter (or pass in new ComplexNumber
instead of ComplexNumber.class
). Then you can replace instanceof
with clazz.equals(ComplexNumber.class)
(and the same for Integer
and Double
).
You're passing in Class<ComplexNumber>
and your else
clause is picking it up, since it's not a ComplexNumber
or an Integer
, it's a Class
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.