
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to get input from the user
In this article, we will understand how to get input from the user in Java. Java provides a built-in Scanner Class that belongs to the java.util package.
The Scanner class is used to get user input. In this article, we will learn how to take different types of input, like integers, floating numbers, strings, etc., from the user in Java.
Algorithm
Following are the steps to get input from the user -
Step 1- START Step-2- Import the Scanner class Step 3- Create a Scanner object Step 4- Prompt the user to enter input Step 5- Use Scanner methods to read input values Step 6- Display it on the console Step 7- STOP
As written in step 5, use the scanner method to read input values. For this, first create an object of the Scanner class, then invoke the appropriate method of the Scanner class, i.e, the type of data you want to get as input from the user.
Methods to Read Input Values
The Scanner class provides different methods for reading different types of input, and they are as follows -
Method | Description |
---|---|
nextBoolean() | Reads a boolean value from the user |
nextByte() | Reads a byte 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 |
nextInt() | Reads an int value from the user |
nextDouble() | Reads a double value from the user |
nextFloat() | Reads a float value from the user |
Steps to Read Data
Following are the steps to get input from users in Java using the Scanner class.
-
First, import the Scanner class from java.util package.
-
Instantiate the Scanner object to read input from the console.
-
Notify the user and prompt input.
-
Use the scanner class's appropriate method to get the input entered by the user and store it in a variable named value.
-
Print the message followed by the user input stored in value.
Example
Here, the input is entered by the user based on a prompt. In this program, nextLine() method is used to read a string value from the user.
import java.util.Scanner; public class PrintString{ public static void main(String[] args){ String value; Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); value = scanner.nextLine(); System.out.println("The string is: "); System.out.println(value); } }
Output
Enter a string: Good Morning! The string is: Good Morning!