需要按两次Enter键,加上nextLine()无法解决问题

时间:2019-03-10 07:22:48

标签: java

我已经研究这个问题已有一段时间了,我以为我找到了解决方案,但无济于事。

我正在创建一个基于文本的游戏,当我要求用户输入他们选择的数字1-4时,他们必须按Enter键两次。无论我的nextInt()是否紧跟nextLine()(我的大部分研究都发现了这一点),我都必须打两次Enter。

public void askPlayer() {
    int playerLocation = player.getCurrentLocationIndex();
    enterRoom(map.getLocationAt(playerLocation));
    Scanner sc = new Scanner(System.in); 
    if(map.hasLeftChild(playerLocation)){
    System.out.println ("Press 1 to go to " + map.getLocationAt(map.getLeftChild(playerLocation)).getName());
    }
    if(map.hasCenterChild(playerLocation)){
    System.out.println ("Press 2 to go to " + map.getLocationAt(map.getCenterChild(playerLocation)).getName());
    }
    if(map.hasRightChild(playerLocation)){
    System.out.println ("Press 3 to go to " + map.getLocationAt(map.getRightChild(playerLocation)).getName());
    }
    if(map.hasParent(playerLocation)){
        System.out.println("Press 4 to go back to " + map.getLocationAt(map.getParent(playerLocation)).getName());
    }
    int choice = sc.nextInt();
    sc.nextLine();
    System.out.println("You picked " + choice);
    super.takeTurn(choice);
}'

感谢您的帮助!

0 个答案:

没有答案