java:类不被识别为自身的示例

zxlwwiss  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(372)

我正在尝试为一些矩阵运算实现一个关联运算符,而且我还必须使用复数。我在运行程序后遇到以下错误:java.lang.arraystoreexception:java.lang.double,我发现这个错误是因为instanceof check传递为false,而它应该是true。
这是我的密码:

  1. public void readFromFile(int noOfLines, int noOfColumns,T[][] matrix,T t) throws FileNotFoundException
  2. {
  3. File file = new File("matrix.txt");
  4. Scanner s = new Scanner(file);
  5. for (int i = 0; i < noOfLines; ++i)
  6. {
  7. for (int j = 0; j < noOfColumns; ++j)
  8. {
  9. if(t instanceof ComplexNumber)
  10. matrix[i][j] = (T)new ComplexNumber(s.nextInt(), 1);
  11. else if(t instanceof Integer)
  12. matrix[i][j] = (T)new Integer(s.nextInt());
  13. else
  14. matrix[i][j] = (T)new Double(s.nextInt());
  15. }
  16. }
  17. }

问题出现在这一行

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

这一行的错误

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

下面是我如何调用函数

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

noofline和noofcolumns是整数,readfromfile从文件中读取一些字符串,它应该将它们放入matrix1数组中。如何解决这个问题,为什么complexnumber.class(或readfromfile参数中的t)和instanceof complexnumber不存在?谢谢您。
编辑:complexnumber类

  1. public class ComplexNumber {
  2. public double real;
  3. public double imag;
  4. public String output = "";
  5. public ComplexNumber(double real, double imag) {
  6. this.real += real;
  7. this.imag += imag;
  8. }
  9. public ComplexNumber() {
  10. real = 0;
  11. imag = 0;
  12. }
  13. public double getReal() {
  14. return real;
  15. }
  16. public void setReal(double real) {
  17. this.real = real;
  18. }
  19. public double getImag() {
  20. return imag;
  21. }
  22. public void setImag(double imag) {
  23. this.imag = imag;
  24. }
  25. public void add(ComplexNumber num2) {
  26. this.real += num2.real;
  27. this.imag += num2.imag;
  28. }
  29. public void subtract(ComplexNumber num) {
  30. this.real -= num.real;
  31. this.imag -= num.imag;
  32. }
  33. public void print() {
  34. System.out.print(real + " " + imag + "i");
  35. }
  36. public String toString() {
  37. return real + " " + imag + "i";
  38. }
  39. }
xam8gpfp

xam8gpfp1#

你需要 Class<T> clazz 而不是 T t 作为参数(或传入 new ComplexNumber 而不是 ComplexNumber.class ). 然后你可以替换 instanceofclazz.equals(ComplexNumber.class) (和 Integer 以及 Double ).
你要过去了 Class<ComplexNumber> 还有你的 else 因为它不是一个 ComplexNumber 或者一个 Integer ,这是一个 Class .

相关问题