找不到java.lang.NullPointerException [英] Can't find java.lang.NullPointerException
本文介绍了找不到java.lang.NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经对该程序进行了编码
这是稀疏矩阵类
I have coded this program
This is sparse matrix class
public class MatrixTerm {
public int row,col,value;
}
class SparsMatrix {
private int Row,Col,Term;
public MatrixTerm SmArray[];
int count=0;
public SparsMatrix(int r,int c,int t){
Row=r;
Col=c;
Term=t;
SmArray =new MatrixTerm [20];
}
public void ReadSparse(){
Scanner input= new Scanner(System.in);
System.out.println("lotfan satr va soton matrix vorodi ra vared konid ");
Row=input.nextInt();
Col=input.nextInt();
int[][] matrix = new int [Row][Col];
for (int i=0;i<row;++i){>
for(int j=0;j<col;++j){>
System.out.println("lotfan "+"("+(i+1)+","+(j+1)+")"+" ra vared konid");
matrix[i][j]=input.nextInt();
}}
for (int i=0;i<Row;++i){>
for(int j=0;j<Col;++j){>
if(matrix[i][j]!=0){
SmArray[i].row=i;/// <big>HERE SAY java.lang.NullPointerException</big>
SmArray[i].col=j;
SmArray[i].value=matrix[i][j];
++count;
}
}
}
}
public void show(){
for(int i=0;i<count;++i){>
System.out.println(SmArray[i]);
}
}
}
当我在第36行测试程序时,它说java.lang.NullPointerException
请帮助我
when i test the program in line 36 it say java.lang.NullPointerException
plz help me
推荐答案
用调试器检查i的值. Row值是动态的,但SmArray的声明是硬编码的20.SmArray =new MatrixTerm [20];
首先,从不调用SparsMatrix,因此不会初始化数组.其次,您可能会考虑使用列表而不是数组,因为列表会根据需要扩展,因此效率更高.
添加以下导入:
Check the value of i with the debugger. The Row value is dynamic but the declaration of the SmArray is hardcoded 20.SmArray =new MatrixTerm [20];
First of all, SparsMatrix is never called so the array isn''t initialized. Second, you might consider using a list instead of an array because a list will expand as needed and therefor more efficient.
Add these imports:
import java.util.Arrays;
import java.util.List;
import java.util.Iterator;
将数组声明更改为通用列表:
Change the array declaration to a generic list:
List smArray<matrixterm> = new ArrayList<matrixterm>();</matrixterm></matrixterm>
更改MatrixTerm以添加构造函数:
Change the MatrixTerm to add a constructor:
public class MatrixTerm {
public int row,col,value;
public MatrixTerm(int row, int col, int value) {
this.row = row;
this.col = col;
this.value = value;
}
}
像这样向smArray添加值:
Add values to smArray like this:
smArray.add(new MatrixTerm(row, col, value));
祝你好运!
Good luck!
这篇关于找不到java.lang.NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文