import java.util.Scanner;
import java.lang.Integer;
public class points{
private class Vertex{
public int xcoord,ycoord;
public Vertex right,left;
}
public points(){
Scanner input = new Scanner(System.in);
int no_of_pts = Integer.parseInt(input.nextLine());
Vertex[] polygon = new Vertex[no_of_pts];
for(int i=0;i<no_of_pts;i++){
String line = input.nextLine();
String[] check = line.split(" ");
polygon[i].xcoord = Integer.parseInt(check[0]);
polygon[i].ycoord = Integer.parseInt(check[1]);
}
}
public static void main(String[] args){
new points();
}
}
这是一个非常简单的程序,我想在系统中输入 n 个点及其 x 和 y 坐标
Sample Input :
3
1 2
3 4
5 6
但是输入“1 2”后它会抛出 NullPointerException 。我使用 Java 调试发现令人不安的行是
polygon[i].xcoord = Integer.parseInt(check[0]);
但是检查变量正确显示 '1' 和 '2' 。出了什么问题?
编辑: 感谢这些答案,我意识到我必须使用将数组的每个元素初始化为一个新对象
polygon[i] = new Vertex();
最佳答案
因为数组中的Vertex引用为空。
import java.util.Scanner;
import java.lang.Integer;
public class points{
private class Vertex{
public int xcoord,ycoord;
public Vertex right,left;
}
public points(){
Scanner input = new Scanner(System.in);
int no_of_pts = Integer.parseInt(input.nextLine());
Vertex[] polygon = new Vertex[no_of_pts];
for(int i=0;i<no_of_pts;i++){
String line = input.nextLine();
String[] check = line.split(" ");
polygon[i] = new Vertex(); // this is what you need.
polygon[i].xcoord = Integer.parseInt(check[0]);
polygon[i].ycoord = Integer.parseInt(check[1]);
}
}
public static void main(String[] args){
new points();
}
}
关于java - 在java中输入数字集 - 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12761081/