Read user input in Java using Scanner

Ads
 

Read user input in Java using Scanner

Java Scanner class can be to read the user input from console. This program teaches you code for reading user input from console using the scanner class.

Java Scanner class can be to read the user input from console. This program teaches you code for reading user input from console using the scanner class.

Example of of reading user input in Java using Scanner

In this section we are explaining the use of Scanner class in Java which can be used to read user input from console. Our sample program asks user to enter name and then age, user input is read using the scanner class. Information entered by user is printed back on the console.

There are various ways to read user input in Java and Scanner class is one of them. Scanner class can be used to read user input from console. It provide methods to read data in String, int, byte, short, Long, Float and Double formats. You can use this class to read and parse data using the regular expression.

Constructor

Scanner class takes input stream as the constructor parameter as shown below:

Scanner  scannerObj=new  Scanner(System.in);

In this above code we are constructing object of Scanner class by passing System.in as input stream. Scanner class is used to read from input stream using regular expressions and it provides methods to read data into various formats.

Example of of reading user input in Java using Scanner

Following are the most used methods of Scanner class:

Method Description
public byte nextByte() Use this method to read byte value from the stream
public short nextShort() If you have to read the short value then use this method
public int nextInt() Function is used to read the int value
public long nextLong() For reading the long value using Scanner class
public float nextFloat() For reading the float value
 public double nextDouble() Used to read value into double variable
public char nextChar() Read a char
public boolean nextBoolean() For reading boolean value
public String nextLine() For reading whole line

So, above are the methods that you can use with the Scanner class object. Now let's make a simple program to reading user input from console.

package net.roseindia;

import java.util.Scanner;

public class ReadConsoleScanner {

	public static void main(String[] args) {

	Scanner scanner = new Scanner(System.in);
	System.out.println("Enter your Name:");
	String name = scanner.nextLine();
	System.out.println("Enter your age:");
	int age = scanner.nextInt();
	System.out.println("Welcome  " +name 
          +"!!! You are "+age+" old!!");

	}
}

Following is the sample output of the program:

Enter your Name:
Deepak
Enter your age:
35
Welcome  Deepak!!! You are 35 old!!

So, in this example we learned to read user input from console, we used Scanner class to read line and int value from the console.

Related Examples:

Ads

Ads