Table of Contents
3 Ways of Java User Input
1. Java BufferedReader Class
Constructors
Functions
2. Java Scanner Class
3. Using console Class
Home Java javaTutorial Java User Input

Java User Input

Aug 30, 2024 pm 04:06 PM
java

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.

3 Ways of Java User Input

There are three ways to read the User Input:

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  1. Java BufferedReader Class
  2. Java Scanner Class
  3. Using console Class

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"));
Copy after login

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.

Code:

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);
}
}
Copy after login

Output:

Java User Input

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);
}
}
Copy after login

Output:

Java User Input

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);
}
}
Copy after login

Output:

Java User Input

3. Using console Class

Using the console class to read the input from the command-line interface. It does not work on IDE.

Code:

public class Main
{
public static void main(String[] args)
{
// Using Console to input data from user
System.out.println("Enter your data");
String name = System.console().readLine();
System.out.println("You entered: "+name);
}
}
Copy after login

Output:

Java User Input

The above is the detailed content of Java User Input. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles