0

I want to read several things ( long, string ) from console but I don't know why for, for example just several first input it works and then it doesn't work for others: below is the code what I'm talking about, it doesn't ask for adress

    public void getInfo(PhoneBook PB)
{
    Scanner keyboard = new Scanner(System.in).useDelimiter("\n");
    String c1 = "yes";
    do {

        System.out.print("Name:");
        PB.setName(keyboard.nextLine());
        System.out.print("Family:");
        PB.setFamily(keyboard.nextLine());
        System.out.print("Address:");
        PB.setAddress(keyboard.nextLine());
        System.out.print("Number:");
        PB.setNumber(keyboard.nextLong());

        System.out.println("Do you want to continue(yes/no)");
        c1 = keyboard.nextLine();
        phoneBooks.add(PB);
    }while (c1.equals("yes"));
}

Thanks in advance

Bita Mirshafiee
  • 600
  • 8
  • 14

1 Answers1

1

When you call nextLong() (or nextInt(), nextDouble(), next()...), you are reading in a token with the Scanner, but are not reading in the end-of-line (EOL) token, thus leaving it dangling. This dangling EOL token will then be scooped up immediately with your next call to nextLine(), and so that call will not get the user's input, messing your program up. To fix this, add an additional call to nextLine()after getting your nextLong(), ignoring any result returned since it will just be the EOL token.

So change this:

System.out.print("Number:");
PB.setNumber(keyboard.nextLong());

System.out.println("Do you want to continue(yes/no)");
c1 = keyboard.nextLine();

to this:

System.out.print("Number:");
PB.setNumber(keyboard.nextLong());

keyboard.nextLine():  // **** add this ****

System.out.println("Do you want to continue(yes/no)");
c1 = keyboard.nextLine();
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • sorry would you please explain a little more the word "swallow" that you use, you mean that we should get the end-of-line characters in scanners? – Bita Mirshafiee Nov 28 '15 at 14:06