You are on page 1of 2

Java Scanner

Scanner class in Java is found in the java.util package. Java provides various ways to read
input from the keyboard, the java.util.Scanner class is one of them.

It provides many methods to read and parse various primitive values.

The Java Scanner class is widely used to parse text for strings and primitive types using a
regular expression. It is the simplest way to get input in Java. By the help of Scanner in
Java, we can get input from the user in primitive types such as int, long, double, byte,
float, short, etc.

The Java Scanner class provides nextXXX() methods to return the type of value such as
1. nextInt()
2. nextByte()
3. nextShort()
4. next()
5. nextLine()
6. nextDouble()
7. nextFloat()
8. nextBoolean()
etc.

To get a single character from the scanner, you can call

next().charAt(0) method which returns a single character.

A program to read name and age using Scanner class


import java.util.* ;
class scannerdemo
{
public static void main(String args[])
{
int age;
String name;
Scanner sc= new Scanner(System.in);
System.out.println("Enter age");
age = sc.nextInt();
System.out.println("Enter name");
name = sc.next();

System.out.println("Hello, "+name);
System.out.println(" Your age is "+age);
}
}
A program to perform arithmetic operations on given two numbers using Scanner class

// A program to find arithmetic calculation on given two numbers


import java.util.*;
class arithdemo2
{
public static void main(String args[])
{
int a;
int b;
int add,sub,mul,rem;
float div;
Scanner sc=new Scanner(System.in);
System.out.println("Enter first number");
a=sc.nextInt();
System.out.println("Enter second number");
b=sc.nextInt();

add=a+b;
sub=a-b;
mul=a*b;
div=(float)a/b;
rem=a%b;

System.out.println("Addition is "+add);
System.out.println("Minus is "+sub);
System.out.println("Product is "+mul);
System.out.println("Division is "+div);
System.out.println("Remainder is "+rem);

}
}

You might also like