我要建立一个宠物商店- =先建立一个animal类
package pethome;
public class Animal {
private int age;
private String name ;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println(getAge()+"\t"+getName());
}
}
然后开始写主函数
package pethome;
import java.util.*;
public class Demo {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
Animal[] animal=new Animal[9];
int k=0;
System.out.println("welcome to the pethome! What do you want to do ? ");
while(true)
{
System.out.println("1.add the pet");
System.out.println("2.delete the pet");
for(int i=0;i<9 ;i++){
if(animal[i]!=null){
animal[i].show();
System.out.println("\n");
}
}
int a=in.nextInt();
switch(a){
case 1:
System.out.println("please inset the name ");
String b=in.nextLine();
animal[k].setName(b);
System.out.println("please inset the age");
int c=in.nextInt();
animal[k].setAge(c);
k++;
break;
}
}
}
}
这个程序我没做完,想测试一下第一个添加宠物的函数。问题是在这里,这是我的运行界面
welcome to the pethome! What do you want to do ?
1.add the pet
2.delete the pet
1
please inset the name
Exception in thread "main" java.lang.NullPointerException
at pethome.Demo.main(Demo.java:27)
说我的animal[]数组没有内存,b和c的值并没有录入到animal【0】的name和age里!
求大神解答
大水萝卜
大水萝卜
相关分类