Scanner skips to the second scan when using scanner.nextLine on first scan

Viewed 36

I have Contact class and it works fine. To add contact I am using the code below

import java.util.Scanner;

public class Main{
 public static void main(String[] args){
    Scanner scanner = new Scanner(System.in);

    System.out.println("ADD NEW CONTACT");
    System.out.println("\tEnter name of contact:");
    String name = scanner.nextLine();
    System.out.println("\tEnter number of contact:");
    String number = scanner.nextLine();
    
    Contact contact = new Contact();
    contact.add(name, number);

 }

}

The problem is it ignores the first scan and skips to Enter number of contact

I know scanner.next() will fix this but I want the name of the contact to have spaces

1 Answers

The problem is not really that the scanner is skipping it, but that you are not fast enough:)! It's not you, though, you would have to type at about 100 words per millisecond to do it! Here's what's happening:

Scanner scanner = new Scanner(System.in);

You create a scanner.

System.out.println("ADD NEW CONTACT");

You print ADD NEW CONTACT.

System.out.println("\tEnter name of contact:");

You print Enter name of contact:.

String name = scanner.nextLine();

The scanner scans within nanoseconds of this println. You are too slow :)!

System.out.println("\tEnter number of contact:");

It prints out Enter number of contact: before you are even aware you had the opportunity to react to the first prompt.

String number = scanner.nextLine();

It now waits patiently, because it has nothing else to do. You, with your mortal reflexes, can now enter the contact number.

So how can you slow the computer to mortal pace? Here are three solutions:

  1. Create a first scanner under 'name' and another under 'contact'. The second scanner will not run until the first scanner has been used.

  2. Create a multi-line process with one scanner which takes two lines, NOT separated by "print this", then "print that".

  3. Use Thread.sleep(), which pauses to give the user time to enter:

     System.out.println("\tEnter name of contact:");
     String name = scanner.nextLine();
     Thread.sleep(3000)//3000 milliseconds = 3 seconds, or however long you want
     System.out.println("\tEnter number of contact:");
    

This puts the process to sleep for the milliseconds you dictate, so that the next println does not execute until that time has passed. Thus, you will be able to enter the contact name without the computer moving on at lightning speed.

Related