Java User Input (Scanner)
The Scanner class is used to get user input, and it is found in the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings:
Example
import java.util.Scanner; // Import the Scanner class class Main < public static void main(String[] args) < Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println("Enter username"); String userName = myObj.nextLine(); // Read user input System.out.println("Username is: " + userName); // Output user input >>
If you don’t know what a package is, read our Java Packages Tutorial.
Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below:
Method | Description |
---|---|
nextBoolean() | Reads a boolean value from the user |
nextByte() | Reads a byte value from the user |
nextDouble() | Reads a double value from the user |
nextFloat() | Reads a float value from the user |
nextInt() | Reads a int value from the user |
nextLine() | Reads a String value from the user |
nextLong() | Reads a long value from the user |
nextShort() | Reads a short value from the user |
In the example below, we use different methods to read data of various types:
Example
import java.util.Scanner; class Main < public static void main(String[] args) < Scanner myObj = new Scanner(System.in); System.out.println("Enter name, age and salary:"); // String input String name = myObj.nextLine(); // Numerical input int age = myObj.nextInt(); double salary = myObj.nextDouble(); // Output input by user System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); >>
Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like «InputMismatchException»).
You can read more about exceptions and how to handle errors in the Exceptions chapter.
Java have user input
- How to maintain polyglot persistence for microservices Managing microservice data may be difficult without polyglot persistence in place. Examine how the strategy works, its challenges.
- Top developer relations trends for building stronger teams Learn about enterprise trends for optimizing software engineering practices, including developer relations, API use, community .
- 5 noteworthy challenges of automotive software development Modern cars are loaded with technology, but creating in-vehicle applications isn’t always a cakewalk. Here are five unique .
- The basics of implementing an API testing framework With an increasing need for API testing, having an efficient test strategy is a big concern for testers. How can teams evaluate .
- The potential of ChatGPT for software testing ChatGPT can help software testers write tests and plan coverage. How can teams anticipate both AI’s future testing capabilities .
- Retail companies gain DORA metrics ROI from specialist tools DORA metrics and other measures of engineering efficiency are popping up in add-ons to existing DevOps tools. But third-party .
- How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
- Prices for cloud infrastructure soar 30% Tough macroeconomic conditions as well as high average selling prices for cloud computing and storage servers have forced .
- Deploy a low-latency app with AWS Local Zones in 5 steps Once you decide AWS Local Zones are right for your application, it’s time for deployment. Follow along in this step-by-step video.
- Microsoft still investigating stolen MSA key from email attacks While Microsoft provided additional attack details and techniques used by Storm-0558, it remains unclear how the Microsoft .
- JumpCloud breached by nation-state threat actor JumpCloud’s mandatory API key rotation earlier this month was triggered by a breach at the hands of a nation-state threat actor .
- XSS zero-day flaw in Zimbra Collaboration Suite under attack A manual workaround is currently available for a cross-site scripting vulnerability in Zimbra Collaboration Suite, though a patch.
- AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
- Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
- Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .
Java User Input
In the Java program, there are 3 ways we can read input from the user in the command line environment to get user input, Java BufferedReader Class, Java Scanner Class, and Console class. Let us discuss the classes in detail. We use the Scanner class to obtain user input. This program asks the user to enter an integer, a string, and float, and it will be printed on display. The scanner class in java.util is present so that we can add this package to our software. First, we create a Scanner Class object and use the Scanner Class method.
Web development, programming languages, Software testing & others
3 Ways of Java User Input
There are three ways to read the User Input:
These three class are mentioned below; let us discuss them in detail:
1. Java BufferedReader Class
It extends reader class. BufferedReader reads input from the character-input stream and buffers characters so as to provide an efficient reading of all the inputs. The default size is large for buffering. When the user makes any request to read, the corresponding request goes to the reader, and it makes a read request of the character or byte streams; thus, BufferedReader class is wrapped around another input streams such as FileReader or InputStreamReaders.
For example:
BufferedReader reader = new BufferedReader(new FileReader("foo.in"));
BufferedReader can read data line by line using the method readLine() method.
BufferedReader can make the performance of code faster.
Constructors
BufferedReader has two constructors as follows:
1. BufferedReader(Reader reader): Used to create a buffered input character stream that uses the default size of an input buffer.
2. BufferedReader(Reader reader, input size): Used to create a buffered input character stream that uses the size provided for an input buffer.
Functions
- int read: It is used for reading a single character.
- int read(char[] cbuffer, int offset, int length): It is used for reading characters in the specified part of an array.
- String readLine (): Used to reading input line by line.
- boolean ready(): Used to test whether the input buffer is ready to read.
- long skip: Used for skipping the characters.
- void close(): It closes the input stream buffer and system resources associated with the stream.
When the user enters the character from the keyboard, it gets read by the device buffer and then from System.in it passes on to the buffered reader or input stream reader and gets stored in the input buffer.
import java.util.*; import java.lang.*; import java.io.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /*package whatever //do not write package name here */ class BufferedReaderDemo < public static void main (String[] args) throws NumberFormatException, IOException < System.out.println("Enter your number"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); System.out.println("Number you entered is: " + t); System.out.println("Enter your string"); String s = br.readLine(); System.out.println("String you entered is: " + s); >>
Program with reading from InputStreamReader and BufferedReader:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BufferedReaderDemo < public static void main(String args[]) throws IOException< InputStreamReader reader = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(reader); System.out.println("What is your name?"); String name=br.readLine(); System.out.println("Welcome "+name); >>
2. Java Scanner Class
java.util. scanner class is one of the classes used to read user input from the keyboard. It is available at the util package. Scanner classes break the user input using a delimiter that is mostly whitespaces by default. The scanner has many methods to read console input of many primitive types such as double, int, float, long, Boolean, short, byte, etc. It is the simplest way to get input in java. Scanner class implements Iterator and Closeable interfaces. The scanner provides nextInt() and many primitive type methods to read inputs of primitive types. The next() method is used for string inputs.
Constructors
- Scanner(File source): It constructs a scanner to read from a specified file.
- Scanner(File source, String charsetName): It constructs a scanner to read from a specified file.
- Scanner(InputStream source), Scanner(InputStream source, String charsetName): It constructs a scanner to read from a specified input stream.
- Scanner(0Readable source): It constructs a scanner to read from a specified readable source.
- Scanner(String source): It constructs a scanner to read from a specified string source.
- Scanner(ReadableByteChannel source): It constructs a scanner to read from a specified channel source.
- Scanner(ReadableByteChannel source, String charsetName): It constructs a scanner to read from a specified channel source.
Functions
Below are mentioned the method to scan the primitive types from console input through Scanner class.
- nextInt(),
- nextFloat(),
- nectDouble(),
- nextLong(),
- nextShort(),
- nextBoolean(),
- nextDouble(),
- nextByte(),
Program to read from Scanner Class:
Using scanner class. import java.util.Scanner; /*package whatever //do not write package name here */ class ScannerDemo < public static void main (String[] args) < Scanner sc = new Scanner(System.in); System.out.println("Enter your number"); int t = sc.nextInt(); System.out.println("Number you entered is: " + t); System.out.println("Enter your string"); String s = sc.next(); System.out.println("String you entered is: " + s); >>
3. Using console Class
Using the console class to read the input from the command-line interface. It does not work on IDE.
Recommended Articles
This is a guide to Java User Input. Here we discuss the 3 ways we can read Java User Input from the user in the command line environment. This article gives you a basic idea of all the inputs you can explore using Java. You may also look at the following article.
89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8
Java have user input
- Introduction to Java
- The complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works – JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
- Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- Interfaces in Java
- ‘this’ reference in Java