0

I am creating some code for a project where I am creating players and countries. It's a country randomizer for a game. I am using while loops to create any number of players and same number of countries.

import java.util.Scanner;
import java.lang.System.*;

public class countryRand
{
   public static void main(String[] args)
   {
      Scanner userInput = new Scanner(System.in); //creates scanner object

      out.println("How many players? "); //asks for input for number of players
      int limit = userInput.nextInt();

      ArrayList<String> players = new ArrayList<String>(); //assigns player names to an array
      for (int index = 0; index < limit; index++)
      {
         out.println("Player" + (index + 1) + " : ");
         players.add(userInput.nextLine()); //this is the problem
         //I tried this code with the number two for number of players. this for loop prints Player1: 
         //and player2: but only takes one input for some reason
      }

      ArrayList<String> countries = new ArrayList<String>(); //assigns country names to an array
      for (int index = 0; index < limit; index++)
      {
         out.println("Country" + (index + 1) + " : ");
         countries.add(userInput.nextLine()); //here, however, it works fine
      }
   }
}
  • Can you get the value of `userInput.nextLine()` in a local variable and then call the method? – Sandeep Kumar Jan 09 '20 at 14:58
  • You are calling `nextLine()` after using `nextInt()` but you didn't consume the line terminator, simply add a line of `userInput.nextLine()` before your `players.add(userInput.nextLine())`(outside of the loop) and and don't store it in a value. – Nexevis Jan 09 '20 at 14:59
  • @Nexevis Thanks, your answer worked! – adityapgupta211 Jan 09 '20 at 17:13

0 Answers0