public?void?createPlayer(){
System.out.println("-----------創建玩家...--------------------");
try?{
for(int?i=1;i<3;i++){
System.out.println("請輸入第"+i+"位玩家的ID和姓名:");
System.out.println("輸入ID:");
Integer?id=input.nextInt();
System.out.println("輸入姓名:");
String?name=input.next();
for?(Player?p?:?playerList)?{//保證ID和姓名不重復。若重復,拋出異常
if(id.equals(p.id)?||?name.equals(p.name))
i=1/0;
}
Player?player=new?Player(id,name);
playerList.add(player);
}
}?catch?(InputMismatchException?e)?{
System.out.println("ID必須為數字!");
input.next();
createPlayer();
}?catch?(Exception?e)?{
System.out.println("ID或姓名不能相同!");
//input.next();??//為什么這句不能留,而上面那句必須要?
createPlayer();
}
for(int?i=0;i<2;i++)
System.out.println("----歡迎玩家:"+playerList.get(i).name);
}見catch塊內,input.next(); ?//為什么這句不能留,而上面那句必須要?
2 回答
已采納

望遠
TA貢獻1017條經驗 獲得超1032個贊
catch?(InputMismatchException?e)?{
????????????System.out.println("ID必須為數字!");
????????????input.next();
????????????createPlayer();
????????}?catch?(Exception?e)?{
????????????System.out.println("ID或姓名不能相同!");
????????????//input.next(); ?
????????????createPlayer();
????????}
因為第一個捕獲的異常是輸入不匹配異常,表示你輸入的id不是整型,比如你輸入id時輸入student,捕獲到異常,程序跳轉到catch塊,這個時候鍵盤輸入的數據就需要一個input.next()來吸收掉原來的錯誤數據student防止數據影響,樓主可以試著打印第一的catch塊中input.next()接收的內容,而第二個catch塊就可以不用吸收數據。

劍術趨于化境
TA貢獻3條經驗 獲得超7個贊
這個紙牌的程序我寫過的,不過被我誤刪了。我學到現在腦子都糊了。你的問題回答不了,不過只有兩個玩家,你就分別創建吧,player1,player2。建第二個玩家的時候做判斷。
添加回答
舉報
0/150
提交
取消