我要建立一個寵物商店- =先建立一個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 pet2.delete the pet1please inset the name?Exception in thread "main" java.lang.NullPointerException at pethome.Demo.main(Demo.java:27)說我的animal[]數組沒有內存,b和c的值并沒有錄入到animal【0】的name和age里!求大神解答
4 回答

大水蘿卜
TA貢獻13條經驗 獲得超9個贊
Scanner類中nextInt()方法,在遇到第一個分隔符(換行或空格)會結束掃描,這個時候,程序讀取的是分隔符之前的數據,并不包括分隔符。
所以,當之后的nextLine()方法掃描時,會第一個掃描到你在nextInt()方法輸入時,輸入的最后一個分隔符,這個時候nextLine()方法就會結束掃描。所以你后面就無法再輸入數據了。
簡單的講,nextInt()方法讀取了你輸入的“1”,而接下來的nextLine()方法讀取了你輸入的“1”之后的回車鍵。而它讀到回車鍵就認為讀取已經結束了。
關于這個問題,你可以去網上搜索一下Scanner類的next()與nextLine()的區別
有不足的地方,歡迎指正,共同進步
添加回答
舉報
0/150
提交
取消