1

I have my code here which simply prompts the user to input the 10 names with their corresponding id number:

import java.util.*;

public class myJava {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    String arr[] = new String [10];
    int arr2[] = new int [10];

    //loop for prompting name and id
    for (int x = 0; x <10; x++)
    { 
        System.out.print("Enter Name: ");
        arr[x] = sc.nextLine();

        System.out.print("Enter ID: ");
        arr2[x] = sc.nextInt();
    }

    //loop for the result
    for (int y = 0; y < 10; y++)
    {
        System.out.println("Name: "+ arr[y]);
        System.out.println("ID: "+ arr2[y]);
    }
}

}

There's no problem with the first loop but in the second loop the program skips to prompt the name and asks for the id. I don't know what's wrong with the code.

This is my Sample Output:

--------------------
Enter Name: User1
Enter ID: 1

Enter Name: Enter ID: 
Makudex
  • 1,042
  • 4
  • 15
  • 40
  • Also found out that it would also work by re-instantiating `sc = new Scanner(System.in);` inside for loop :) – Makudex Sep 04 '15 at 09:07

1 Answers1

2

Skip the line after reading int

 System.out.print("Enter Name: ");
 arr[x] = sc.nextLine();

 System.out.print("Enter ID: ");
 arr2[x] = sc.nextInt();
 sc.nextLine();   //will eat up the remaining line left after reading token by above line

because nextInt() consume the token not the whole line

singhakash
  • 7,891
  • 6
  • 31
  • 65