我想为我的项目寻求帮助。我是新手程序员,我没有收到此错误 "exception in thread main java.lang.nullpointerexception"
这是我的代码:
public class Slumbook{
public String codeName;
public Slumbook(){
//
}
public Slumbook(String codeName){
this.codeName = codeName;
}
public String getCodeName(){return codeName;}
public void setCodeName(String codeName){this.codeName = codeName;}
}
Driver Program
代码为: -
import java.util.*;
public class SlumbookD{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Slumbook[] slum = new Slumbook[20];
for(int n=0; n<10; n++){
slum[n].setCodeName(sc.nextLine());
}
}
}
答案 0 :(得分:2)
您已分配数组...但您未能分配数组中包含的任何对象。
建议:
import java.util.*;
public class SlumbookD {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Slumbook[] slum = new Slumbook[20];
for(int n=0; n<slum.length; n++){
slum[n] = new Slumbook(sc.nextLine);
}
}
}
......或更好......
// You only need one class - with it's own main(). Not two classes...
public class Slumbook{
public String codeName;
public Slumbook(String codeName){
this.codeName = codeName;
}
public String getCodeName(){
return codeName;
}
public void setCodeName(String codeName){
this.codeName = codeName;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Slumbook[] slum = new Slumbook[20];
for(int n=0; n<slum.length; n++){
slum[n] = new Slumbook(sc.nextLine);
}
}
}
答案 1 :(得分:1)
您已创建空白数组但未初始化它,您必须将数组索引处的对象引用与相关联,然后您可以在该索引上调用任意数量的setter方法。
Slumbook[] slum = new Slumbook[20];
for(int n=0; n<10; n++){
slum[n] = new Slumbook(); // Instantiate Slumbook class and assign reference
slum[n].setCodeName(sc.nextLine());
}
答案 2 :(得分:0)
您需要在使用之前初始化Array元素。
Slumbook[] slum = new Slumbook[20];
for(int n=0; n<10; n++){
slum[n] = new Slumbook();
slum[n].setCodeName(sc.nextLine());
}
您可以一次初始化数组的所有元素,以避免将来出现任何异常
Slumbook[] slum = new Slumbook[20];
for(int i = 0 ; i < slum.length ; i++) //initializing all the elements
slum[i] = new Slumbook();
for(int n=0; n<10; n++){
slum[n].setCodeName(sc.nextLine());
}