Scanner class in java

Previous
Next

Scanner:

  • Scanner class is used to read input from the user.
  • Scanner class can read the data from different input sources like KEYBOARD, FILE …..
  • Look at the constructors of Scanner class – No default constructor

We must specify the input source while creating object.

Construct Scanner object by passing keyboard object:

  • Java.lang.System class is providing pre-defined keyboard object.
  • “in” is a static variable in System class.
  • “in” is a pre-defined keyboard object of “InputStream” type

Note: As these variables are static type, we access using class name “System”

Code: Object creation of Scanner class

import java.util.Scanner;
class ReadInfo 
{
	public static void main(String[] args) 
	{
		Scanner scan = new Scanner(System.in);
	}
}

How to read input using Scanner object?

  • Scanner class is providing different non static methods to read input from user.
  • We call these instance methods using Scanner class object.
  • For every primitive type, there is a corresponding method to read.
import java.util.Scanner;
class ReadInfo 
{
	public static void main(String[] args) 
	{
		Scanner scan = new Scanner(System.in);
		System.out.print("Enter integer : ");
		int x = scan.nextInt();
		if(x>0)
			System.out.println("Posivite");
		else if(x<0)
			System.out.println("Negative");
		else
			System.out.println("Zero");
	}
}

Addition code logic:

import java.util.Scanner;
class Addition 
{
	public static void main(String[] args) 
	{
		Scanner scan = new Scanner(System.in);
		System.out.print("Enter integer : ");
		int x = scan.nextInt();
		int y = scan.nextInt();
		System.out.println("Sum of " + x + " & " + y + " is : " + (x+y));
	}
}

Create object of Test class by reading input values:

import java.util.Scanner ;
class Test
{
	int a,b;
	Test(int a, int b)
	{
		this.a = a;
		this.b = b;
	}
	void details()
	{
		System.out.println("a val : " + this.a);
		System.out.println("b val : " + this.b);
	}
}
class ConstructObject 
{
	public static void main(String[] args) 
	{
		Scanner scan = new Scanner(System.in);
		System.out.println("Enter a, b values : ");
		int a = scan.nextInt();
		int b = scan.nextInt();
		Test obj = new Test(a, b);
		obj.details();
	}
}
Previous
Next

Add Comment

Courses Enquiry Form