扫描仪输入两次输入以读取新行

时间:2016-03-10 13:53:01

标签: java java.util.scanner

在这个程序中,用户可以为RPS游戏输入他们想要的名字和轮次数,但是当我尝试输入轮数时,我必须输入两次数字才能让扫描仪读取它。我知道这很简单,但我尝试使用kb.nextInt()和kb.nextLine()来吃掉额外的空间,但没有任何效果。

import java.util.*;
public class RPS
{
   public static void main (String args[])
   {
       Player player = new Player();
   Game game = new Game();
   Scanner kb = new Scanner (System.in);
   int rounds=0;
   String playerName;
   player.setPlayerName();
   playerName = player.getPlayerName();
   System.out.print("Enter number of rounds: ");
   rounds = kb.nextInt();
   while (rounds>0)
   {
       System.out.println("\nEnter your throw (1=Rock, 2=Paper, 3=Scissors): ");
       player.getThrow();
       int pThrow = player.getPlayerThrow();
       System.out.println(playerName+" threw "+getName(pThrow));
       game.makeCompThrow();
       System.out.println("Computer threw "+getName(game.getCompThrow()));
       if(game.announceWinner(pThrow, playerName))
       {
           rounds--;
        }
    }
   game.bigWinner(); 

}
public static String getName(int pcthrow)
{
    if (pcthrow == 1)
    {
        return "ROCK";
    }
    if (pcthrow == 2)
    {
        return "PAPER";
    }
    if (pcthrow == 3)
    {
        return "SCISSORS";
    }
    return null;
}

}

以下是示例输出:

Enter the players name: Bob

Enter number of rounds: 2 // <---- This is where the error is

2 // <--- You have to enter this number twice for it to work

Enter your throw (1=Rock, 2=Paper, 3=Scissors): 
2

Bob threw PAPER

Computer threw SCISSORS

Computer wins!

Enter your throw (1=Rock, 2=Paper, 3=Scissors): 

1

Bob threw ROCK

Computer threw PAPER

Computer wins!

Computer wins 2. Bob wins 0.

Computer is the winner!

1 个答案:

答案 0 :(得分:0)

这是因为nextInt不会将新行(输入键)作为其数据。要解决这个问题。之后添加一个空的nextLine()。这将采用换行符并且没有任何问题地工作。

rounds = kb.nextInt();
kb.nextLine();