java-user-input-–-scanner,-bufferedreader-and-console

“`html

Obtaining user input forms a fundamental aspect of developing interactive Java applications. Whether you’re crafting a console-based utility, a form-driven platform, or even a game, the ability to read and manage user input is crucial. Java provides several techniques – Scanner, BufferedReader, and Console – to capture different types of input like strings, numbers, and characters. This guide will explore each input method, complete with examples, recommended practices, and common challenges for both novice and experienced programmers, enabling them to create engaging and responsive Java applications.

Table of Contents:

Understanding User Input in Java

User input in Java refers to the acquisition of information provided by users while the application is in execution. Java provides various methods for reading user input, with the keyboard (console input) being the most common.

This input serves to create interactive applications by inquiring a user’s name, age, or any other data that the program will process.

Java permits user input through three primary methods:

  • Scanner (from java.util package): Easiest and most commonly utilized by beginners.
  • BufferedReader (from java.io package): More effective for processing large volumes of data or many lines.
  • Console (from java.io.Console): Useful for command-line applications but not universally supported (e.g., in some IDEs).

Each of these methods serves distinct roles depending on performance, ease of use, and compatibility with different environments.

Java Training
This comprehensive course in the Java programming language is designed to advance your software development career
quiz-icon

Techniques for Capturing User Input in Java

Java allows input acquisition through three distinct methods: Scanner, BufferedReader, and Console. The Scanner class is user-friendly and reads inputs from various data types, such as integers, doubles, and strings. BufferedReader is faster and more effective for large data inputs, but it necessitates manual conversion since it only delivers results as strings. The Console class is intended for secure input, such as passwords.

1. Scanner class in Java

The Scanner class, located in the java.util package, is the most prevalent method for obtaining user input in Java. It can read input values from the console, files, or streams. Prior to Java 5, the BufferedReader class was the standard method.

This class doesn’t require any additional installations or downloads. It is built to process primitive data types and strings using regular expressions. Hence, it can automatically interpret input as integers, double values, and strings, functioning seamlessly in all environments, including IDEs.

To read input from a file, we can pass an instance of the Scanner class containing a file. The Scanner class reads an entire line and breaks it down into tokens. Tokens are basic elements that carry significance for the Java compiler.

For instance, if there is an input string: “How do you do?”
The scanner object will read the full line and separate the string into tokens, namely “How”, “do”, and “you”. The object then processes each token using various methods.

Steps for Capturing Input Using the Scanner Class

The following steps outline how to obtain user input using the Scanner class:

1. Import the Scanner class using import java.util.Scanner;

import java.util.Scanner;

2. Create the Scanner object and link Scanner with System.in by passing it as a parameter, i.e.

Scanner scn = new Scanner(System.in);

3. Prompt the user for input by displaying a message.

4. Employ appropriate methods from the Scanner class to read input pertinent to the required data type, like nextInt(), nextLine(), next(), or nextDouble().

5. Close the Scanner to release resources.

scn.close();

Note: The Scanner class should be terminated when it is no longer required as it aids in freeing up resources.

“““html

Exercise caution when terminating the scanner class, as closing it will also shut down System.in, potentially impacting other sections of the program that require input from the console.

Functions of the Scanner Class

The Scanner class offers a variety of functions to capture different kinds of input from the user:

Function Details
nextBoolean() Retrieves a boolean value (true or false).
nextByte() Retrieves a byte value.
nextDouble() Retrieves a double (decimal) value.
nextFloat() Retrieves a float (decimal) value.
nextInt() Retrieves an int (integer) value.
nextLine() Retrieves a full line of text.
nextLong() Retrieves a long (large integer) value.
nextShort() Retrieves a short (small integer) value.
next() Retrieves a single word (up to a space).
nextBigInteger() Retrieves a BigInteger value.
nextBigDecimal() Retrieves a BigDecimal value.
hasNext() Verifies if there’s another token available in the input.
hasNextBoolean() Verifies if the next token is a boolean.
hasNextByte() Verifies if the next token is a byte.
hasNextDouble() Verifies if the next token is a double.
hasNextFloat() Verifies if the next token is a float.
hasNextInt() Verifies if the next token is an int.
hasNextLine() Verifies if there’s another line of input.
hasNextLong() Verifies if the next token is a long.
hasNextShort() Verifies if the next token is a short.

Java Scanner Delimiter

By default, the Scanner class utilizes whitespace, such as spaces and the Enter key, to delimit input values. However, this can be customized using the useDelimiter() function, which allows users to define a specific delimiter like commas, semicolons, or any other character of their choice.

Example: Implementing a Comma as a Delimiter

Java

Code Copied!

var isMobile = window.innerWidth “);

editor88426.setValue(decodedContent); // Set the default text editor88426.clearSelection();

editor88426.setOptions({ maxLines: Infinity });

function decodeHTML88426(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard88426() { const code = editor88426.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { // alert(“Code copied to clipboard!”);

jQuery(“.maineditor88426 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor88426 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode88426() {

var code = editor88426.getSession().getValue();

jQuery(“#runBtn88426 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”,

data: { language: “java”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output88426”).html(“

"+data+"");
									jQuery(".maineditor88426 .code-editor-output").show();
									jQuery("#runBtn88426 i.run-code").hide();
									
								}
							})
					

						}
						
						
		function closeoutput88426() {	
		var code = editor88426.getSession().getValue();
		jQuery(".maineditor88426 .code-editor-output").hide();
		}

    // Attach event listeners to the buttons
    document.getElementById("copyBtn88426").addEventListener("click", copyCodeToClipboard88426);
    document.getElementById("runBtn88426").addEventListener("click", runCode88426);
    document.getElementById("closeoutputBtn88426").addEventListener("click", closeoutput88426);
 
    

Result:

Java-Scanner-Delimiter

Clarification: The preceding code illustrates how to apply a custom delimiter using the Scanner class in Java. The useDelimiter(“,”) method enables the specification of a comma as the delimiter.

``````html function serves to utilize the comma as the separator, and subsequently, the while loop fetches and displays its value.  

Managing Multiple Inputs in the Scanner Class

When gathering several user inputs, we can append an if statement prior to each entry, which can complicate and lengthen the program. To mitigate this, the Scanner class offers integrated exception management.

If the data entered by the user cannot be adequately processed, the Scanner method may raise exceptions such as:

  • NoSuchElementException: This is raised when no further input is accessible, yet a method is invoked to retrieve input.
  • InputMismatchException: This occurs when the input does not align with the anticipated data type, for instance, inputting a string when an integer is sought.

By employing methods like hasNextInt(), hasNextDouble(), etc., we can verify user input before retrieving it to prevent exceptions.

Illustration: Managing the Input Mismatch Exception

Java
Code Copied!

In the above program, if the user inputs an integer, there will be no error message, and the program will execute successfully, displaying the expected outcome.

Handling-Multiple-Inputs-in-Scanner-Class

Conversely, if the user types a string when an integer is needed, an error message will be shown as depicted below.

Handling-Multiple-Inputs-in-Scanner-Class-1

2. BufferedReader Class in Java

The BufferedReader class in Java reads a sequence of characters from a character-based input stream. It is frequently utilized in conjunction with FileReader or InputStreamReader to enhance performance when reading substantial files or streams. InputStreamReader is a method in Java that transforms the input stream into a sequence of characters for BufferedReader to process.

The BufferedReader class employs read() and readLine() methods to read characters from input.

Steps to Capture Input from the User Using the BufferedReader Class

The following are the procedures to gather user input utilizing the BufferedReader class:

1. Import the BufferedReader class using import java.io.BufferedReader;

import java.io.BufferedReader 

2. Instantiate the BufferedReader object 

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

3. Read the Input by Using readLine()

System.out.print("Enter your name: ");

String name = br.readLine();  // Captures a full line of input

4. Handle the Input

System.out.println("Hello, " + name + "! You are " + age + " years old.");

5. Close the BufferedReader to free the resources

br.close();

 Illustration:

``````html

Java

Code Copied!

var isMobile = window.innerWidth ");

editor56756.setValue(decodedContent); // Set the default text editor56756.clearSelection();

editor56756.setOptions({ maxLines: Infinity });

function decodeHTML56756(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard56756() { const code = editor56756.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor56756 .copymessage").show(); setTimeout(function() { jQuery(".maineditor56756 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode56756() { var code = editor56756.getSession().getValue();

jQuery("#runBtn56756 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "java", code: code, cmd_line_args: "", variablenames: "", action: "compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output56756").html("

" + data + "

"); jQuery(".maineditor56756 .code-editor-output").show(); jQuery("#runBtn56756 i.run-code").hide(); } }); }

function closeoutput56756() { jQuery(".maineditor56756 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn56756").addEventListener("click", copyCodeToClipboard56756); document.getElementById("runBtn56756").addEventListener("click", runCode56756); document.getElementById("closeoutputBtn56756").addEventListener("click", closeoutput56756);

Output:

using-the-BufferedReader-class

Explanation: The preceding Java program gathers user input utilizing the BufferedReader class. It first prompts for the user’s name and reads it as a string. Then, it inquires about the user’s age, captures it, and converts it to an integer. In conclusion, it outputs a greeting message and closes the BufferedReader.

Methods of the BufferedReader Class

Below is a table that illustrates the methods that the BufferedReader employs to read user input in Java.

Method Description
readLine() Reads a complete line of text as a string.
read() Reads a single character as an integer. Returns -1 if it reaches the end of the stream.
skip(long n) Skips n characters while reading.
ready() Returns true if the stream is prepared for reading; otherwise, false.
mark(int limit) Marks the current position in the stream.
reset() Resets the stream.
close() Closes the BufferedReader to release resources.

Reading Diverse Data Types with BufferedReader

Since BufferedReader solely reads strings, it is necessary to manually convert the input into other data types.

Example: Reading an Integer

System.out.print("Enter your age: ");

int age = Integer.parseInt(br.readLine()); // Convert String to int

Example: Reading a Double

System.out.print("Enter your salary: ");

double salary = Double.parseDouble(br.readLine()); // Convert String to double

Benefits of BufferedReader

1. Quicker Input Handling: It effectively reads large data.

2. Efficient for Substantial Data: It is ideal for reading large files and handling extensive inputs.

3. Reads Full Lines: It can capture the entire line using the readLine().

4. Reduced Memory Consumption: It utilizes a buffer to store the input, minimizing interactions with the input stream.

5. Supports Character Streams: It is capable of managing character-based input, making it valuable for text processing.

Drawbacks of BufferedReader

1. Only Reads Strings: It returns input solely in string format, necessitating manual conversion for numerical values.

2. Requires More Code: It demands additional coding for managing various data types.

``````html
t necessitates an additional procedure to transform the input data type.

3. Absence of Inherent Input Validation: It does not verify the validity of the input type.

4. Checked Exception Management: It mandates the management of IOException utilizing try-catch or the throws keyword.

3. Console Class in Java

The Console class in Java serves to acquire user input from the system's console command-line interface. It forms a part of the java.io package and is advantageous for interactive applications.

Benefits of Console Class

1. Safe Input Management: It enables users to securely enter their passwords. The readPassword() function permits users to input passwords without showing them on the display, enhancing security.

2. Optimal for Command-Line Applications: It performs effectively in terminals such as Command Prompt, Terminal, and PowerShell. It is suitable for applications where IDEs are unnecessary, for instance, remote server applications.

Drawbacks of Console Class

1. Incompatibility with IDEs: In most IDEs like Eclipse, IntelliJ, and NetBeans, System.console() yields null since IDEs do not utilize a system console for executing Java programs.

2. Constrained Input Abilities: It solely returns String input, meaning you must convert it to another data type using Integer.parseInt(), Double.parseDouble(), and so forth.

Example:

Java

Code Copied!

var isMobile = window.innerWidth ");

editor46068.setValue(decodedContent); editor46068.clearSelection();

editor46068.setOptions({ maxLines: Infinity });

function decodeHTML46068(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

function copyCodeToClipboard46068() { const code = editor46068.getValue(); navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor46068 .copymessage").show(); setTimeout(function() { jQuery(".maineditor46068 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode46068() { var code = editor46068.getSession().getValue(); jQuery("#runBtn46068 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "java", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1]; jQuery(".output46068").html("

"+data+"

"); jQuery(".maineditor46068 .code-editor-output").show(); jQuery("#runBtn46068 i.run-code").hide(); } }); }

function closeoutput46068() { var code = editor46068.getSession().getValue(); jQuery(".maineditor46068 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn46068").addEventListener("click", copyCodeToClipboard46068); document.getElementById("runBtn46068").addEventListener("click", runCode46068); document.getElementById("closeoutputBtn46068").addEventListener("click", closeoutput46068);

Output:

Disadvantages-of-Console-Class-Limited-input-capabilities

Comparison Between BufferedReader and Scanner Class in Java

Let’s explore the distinctions between the BufferedReader class and the Scanner class in Java.

Characteristic BufferedReader Scanner
Speed Quicker (utilizes buffering) Slower (token-oriented)
User-Friendliness Demands manual conversion Convenient to use
Data Read Only strings (requires conversion) Strings, numbers, booleans
Optimal Usage Large files, performance-focused General user input
Exception Management Requires try-catch (IOException) Inbuilt exception management
Memory Usage Low (utilizes buffering) Higher (processes input)
Capabilities readLine() nextInt(), nextLine(), nextDouble(), etc.

Let’s examine the differences between the BufferedReader class and the Scanner class in Java

``````html
Complimentary Online Java Certification Course
This complimentary Java course is tailored for anyone keen on mastering Java and aiming for a career as a Java Developer.
quiz-icon

Final Thoughts

In Java, programmers can utilize a Scanner, a BufferedReader, or a Console to capture user input. The Scanner is user-friendly and supports various data types for input. The BufferedReader class enhances performance when dealing with substantial inputs, but the user must manually convert data types. The Console class securely manages input, such as passwords, but is not functional within IDEs.

If you're interested in furthering your Java knowledge, you can check out our Java Course.

Java User Input: Scanner, BufferedReader, and Console – Frequently Asked Questions

Q1. How can I read input from the System in Java?

To read input, we employ the Scanner tool provided by Java.

Q2. How can I obtain input from a user in Java without utilizing a Scanner?

Employing the Buffered Reader Class, this is the traditional method to collect input in Java.

Q3. How can I invoke a method in Java?

To invoke a method in Java, simply write the method name followed by parentheses (), followed by a semicolon (;).

Q4. How can I read a file using Java?

You can utilize the readLine() method from java.io.BufferedReader to read a file. This method returns null upon reaching the end of the file.

Q5. What distinguishes Scanner from BufferedReader?

In Java, BufferedReader efficiently reads text from a character input stream, while Scanner retrieves input from various sources, including streams, converting input into tokens and primitive types.

Q6. How can I access a file in Java?

There are multiple methods to read a plain text file in Java, such as using FileReader, BufferedReader, or Scanner to read the text file. 

The article Java User Input – Scanner, BufferedReader and Console first appeared on Intellipaat Blog.

```


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This