How in the piece of the following code to allow not to enter middleName ? When I just press Enter, the transition to the next action does not occur.

 Scanner in = new Scanner(System.in); String name; String surname; String middleName; String address; String joinDate; System.out.print("Add new employee\nEnter employee name: "); name = in.next(); System.out.print("Enter employee surname: "); surname = in.next(); System.out.print("Enter employee middle name: "); middleName = in.next(); System.out.print("Enter employee address: "); address = in.next(); 

this code didn't help

 if (in.hasNextLine()) { middleName = in.next(); } else { middleName = null; } 
  • and what is determined разрешить не вводить ? that is, just enter the person clicked and went to enter the address? or to give somewhere the opportunity to not even go to the item enter employee middle name ? - Alexey Shimansky
  • @ Alexey Shimansky Writing the opportunity to press enter, thus the employee will have a null middlename - Ilya Zhavoronkov

1 answer 1

I would recommend not using Scanner for such input. Use BufferedReader :

 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(final String[] args) throws IOException { final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter employee middle name: "); final String middleName = reader.readLine(); System.out.println("middleName = '" + middleName + "'"); } } 

If, however, you really want to use the Scanner , then at least use it correctly, i.e. nextLine method, not next :

 import java.io.IOException; import java.util.Scanner; public class Main { public static void main(final String[] args) throws IOException { final Scanner in = new Scanner(System.in); System.out.print("Enter employee middle name: "); final String middleName = in.nextLine(); System.out.println("middleName = '" + middleName + "'"); } }