0

I'm making a program where I am using a for loop to prompt the user to input a value that will be inserted into an array, where the array is initialized to a number that the user has input and thus the loop runs through that many times as well.

import java.util.Scanner;
public class Borda {
   public static void main(String[] args)
   {
      Scanner keyboard = new Scanner(System.in);
      
      System.out.print("Please enter the number of candidates: ");
      int candidateCount = keyboard.nextInt();

      String[] nameStrings;
      nameStrings = new String[candidateCount];

      for (int i = 0; i < candidateCount; i++)
      {
         System.out.print("Please enter the name of candidate " + (i + 1) + ":" );
         nameStrings[i] = keyboard.nextLine();
      }

      System.out.println(nameStrings[0]);
   }
}

When I compile and run this code, the loop seems to just ignore the keyboard.nextLine(); operation and skip to the second pass of the loop. Can anyone tell me how I can fix this so that it just displays "Please enter the name of candidate 1:" on the first pass and lets the user input a String? The 0 position in the array is just being left empty, the System.out.println(nameStrings[0]); is just a test to see if it's working.

I've tried running this program with a debug and stepping through the whole program, but I can't find the reason.

0 Answers0