0

I need to create a for loop that fills 2 arrays I have set up. However whenever I run the program. It keeps skipping the next prompt and read in and I have no idea why? My code is below. It skips the part where I ask them to enter a sentance/word.

import java.util.Scanner;
/**
 * Created by IntelliJ IDEA.
 * Date: 18/02/2015
 * Time: 15:33
 * UPDATE COMMENT ABOUT PROGRAM HERE
 */
public class Week5Q2
{
   public static void main(String[] args)
   {

      final int HOWMANY=5;
      Scanner keyboard= new Scanner(System.in);
      int choice;

      int number [] = new int [5];//mechanism1
      String sentence [] = new String [5];


      for(int count=0;count<HOWMANY;count++)
      {

         System.out.println("Please enter a number below");
         number[count]=keyboard.nextInt();


         System.out.println("\nPlease enter a word below");
         sentence[count]=keyboard.nextLine();


      }//for

      System.out.println("Thank you, now press 1 if you wish to see what you have entered");
      choice=keyboard.nextInt();

      switch(choice)
      {
         case 1:

            for(int count=0;count<HOWMANY;count++)
            {
               System.out.println("Here are your numbers");
               System.out.println("\n" + number[count]);

               System.out.println("Here are your words");
               System.out.println("\n" + sentence[count]);

            }//for
      }//switch




   }//main
}//class

1 Answers1

0

You must call nextLine() after nextInt(), to consume the end of the line that contained the int. Otherwise, the end of the line will be consumed when you expect to read the sentence/word.

  for(int count=0;count<HOWMANY;count++)
  {

     System.out.println("Please enter a number below");
     number[count]=keyboard.nextInt();

     keyboard.nextLine();

     System.out.println("\nPlease enter a word below");
     sentence[count]=keyboard.nextLine();


  }//for
Eran
  • 387,369
  • 54
  • 702
  • 768