User Program Communication

User Input in Java

Used to accept text input from the user.


Syntax
import java.util.Scanner; //Must import the scanner class at the beginning of the program

Scanner userInput = new Scanner(System.in);
variable = userInput.next();
userInput.close();

Notes

Using the Scanner class, the program can accept input from the user.

The scanner class needs to be imported to the Java program. Scanner is the class name, userInput is the instance of the Scanner class. An instance of the scanner class is created, and from the object, a method can be called to take and parse the input. Once the scanner object is finished accepting input, it is closed to prevent a memory leak.

Next() takes in the user's input, and breaks it up using a delimiter (usually a space). There several different Next methods that can be used. Most are used to restrict the type of data the user can input (for example, nextInt() ensures the user's input is an integer).

When finished, the Scanner object needs to be closed using the close() method.


Example
import java.util.Scanner;

Scanner userInput = new Scanner(System.in);
System.out.print("What is your full name?");
String name = userInput.nextLine();
userInput.close();
System.out.print("Your name is " + name); //Output is 'Your name is (contents of name)'

See Also
Documentation

Java Docs - Scanner Class

Add to Slack

< Print   |   Commenting >

© 2019 SyntaxDB. All Rights Reserved.