简体   繁体   中英

Scanner enter Input twice to read on new line

In this program, the user can input their name and number of rounds they want for the RPS game, but when I try and enter the number of rounds, I have to enter the number twice for the scanner to read it. I know it's something simple, but i've tried using kb.nextInt() and kb.nextLine() to eat that extra space, but nothing works.

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;
}

}

Here is a sample output:

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!

This is because the nextInt will not take the new line (enter key) as its data. To fix it. add a empty nextLine() after that. That will take the newline character and work without any problem.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM