0

When I run the following code it takes the name as input, also the code but then then it bypass the address and the program stops! What is the Problem?

import java.util.Scanner;
class demo
{
    public static void main(String args[])
    {
        Scanner input = new Scanner(System.in);
        String name;
        String address;
        int code;
        System.out.println("Enter Your NAME : ");
        name = input.nextLine();
        System.out.println("Enter Your CODE : ");
        code = input.nextInt();
        System.out.println("Enter Your ADDRESS : ");
        address = input.nextLine();
    }
}
Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145
Rush W.
  • 1,321
  • 2
  • 11
  • 19

1 Answers1

0

Add input.nextLine(); after code = input.nextInt(); to accept the carriage return character left behind by the nextInt()

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • but can you tell me why is this happening? – Rush W. Oct 17 '14 at 16:48
  • @Spider - When you use `nextInt()`, if you enter say `5` and hit Enter, the carriage return character will be still in the stream. Only the number will be read. The `nextLine()` will read it and thus you will think that address has been skipped. So, add a `input.nextLine()` after call to `nextInt()' to gobble up that character. – TheLostMind Oct 17 '14 at 16:51