package com.joker.test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Scanner; import com.joker.entity.Player; import com.joker.entity.Poker; public class PokerGame { Map<Integer, Player> playerMap; List<Poker> pokerList; Scanner input; String[] type = { "黑桃", "红桃", "梅花", "方块" }; String[] pointer = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" }; public PokerGame() { pokerList = new ArrayList<Poker>(); input = new Scanner(System.in); } /** * 创建扑克牌 * * @param args */ public void pokerAdd() { System.out.println("-------创建扑克牌-------"); for (int i = 0; i < type.length; i++) { for (int j = 0; j < pointer.length; j++) { pokerList.add(new Poker(type[i], pointer[j])); } } System.out.println("-------扑克牌创建成功-------"); } /** * 遍历显示所有扑克牌 * * @param args */ public void pokerGet() { for (Iterator<Poker> it = pokerList.iterator(); it.hasNext();) { for (int i = 0; i < type.length; i++) { for (int j = 0; j < pointer.length; j++) { Poker poker = it.next(); System.out .print(poker.getType() + poker.getPointer() + " "); } System.out.println(); } } } /** * 创建玩家 * * @param args */ public void playerAdd() { System.out.println("-------创建玩家-------"); int i = 0; while (i < 2) { System.out.println("请输入玩家的ID:"); int id; try { id = input.nextInt(); Player playerID = playerMap.get(id); if (playerID == null) { System.out.println("请输入玩家的姓名:"); String name = input.next(); Player player = new Player(id, name); playerMap.put(id, player); System.out.println("成功创建玩家:" +playerMap.get(id).getName()); System.out.println("--------------------"); i++; } else { System.out.println("该ID已被占用~~"); continue; } } catch (Exception e) { System.out.println("请输入整数类型ID!!"); continue; } } } public static void main(String[] args) { PokerGame pg = new PokerGame(); pg.pokerAdd(); pg.pokerGet(); pg.playerAdd(); } }
为什么我在try-catch语句中会出现死循环错误输出???求大神指导该怎么改??
Scanner 对象最好不要重复使用,在id=input.nextInt();上面新建一个Scanner对象就可以了,要放在try语句块中,我也遇到了这样的问题,就是这样解决的
按方法修改后,你的代码仍有bug
73行抛出java.lang.NullPointerException。
在创建玩家方法中playerAdd() 的
id=input.nextInt();上面添加一句这个试试
Scanner input=new Scanner(System.in);