Java Input Scanner


Java Input Scanner: It is necessary to take input from the user in every language. This is the way the user can interact with a running program. Java gives three styles of user input – through command-line arguments, though GUI and through keyboard.

Again there are three styles of taking input through keyboard – using byte streams DataInputStream, using character streams BufferedReader and using java.util.Scanner class. Of all, Scanner is easier to code requiring no parsing.

Following example is on Java Input Scanner
import java.util.Scanner;
public class KeyboardScanner
{
 public static void main(String args[])
 {
   Scanner scan = new Scanner(System.in);
					// start taking input
   System.out.println("Enter Your Name:");
   String name = scan.nextLine();

   System.out.println("Enter Your Age:");
   int age = scan.nextInt();
 
   System.out.println("Enter Your Salary:");
   double salary = scan.nextDouble();
					// now display
   System.out.println("Your Name is " + name);
   System.out.println("Your Age is " + age);
   System.out.println("Your Salary is Rs." + salary);
 }
}

Java Input Scanner Output Screenshot on Java Input Scanner

System.in is implicitly connected to the input mechanism of OS. Scanner connects to OS mechanism through System.in. The nextLine() method returns a string, nextInt() returns int and nextDouble() returns a double value. Here parsing is not required.

Read all styles of Keyboard Input in Java:

1. Keyboard Input – Byte Streams – DataInputStream
2. Keyboard Input – Character Streams – BufferedReader
3. Keyboard Input – java.util.Scanner – No parsing

Leave a Comment

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