我要建立一個(gè)寵物商店- =先建立一個(gè)animal類(lèi)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());? ? ? ? }}?然后開(kāi)始寫(xiě)主函數(shù)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; } } }} 這個(gè)程序我沒(méi)做完,想測(cè)試一下第一個(gè)添加寵物的函數(shù)。問(wèn)題是在這里,這是我的運(yùn)行界面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)說(shuō)我的animal[]數(shù)組沒(méi)有內(nèi)存,b和c的值并沒(méi)有錄入到animal【0】的name和age里!求大神解答
4 回答

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