☞As you know predefined classes are inside packages. So we have to import the package first.
☞Scanner class is a member of java.util package.
☞To include the Scanner class in our program, we need to import java.util package and the class.
import java.util.*; or import java.util.Scanner;
☞To use the functions of Scanner class, you need to create an object of Scanner class.
Scanner sc = new Scanner(System.in);
☞Following are the functions of Scanner class that you can use to input data of particular type. Syntax for getting input : <data_type> <variable_name> = <scanner_object>.<function_name>
nextBoolean() ➺ To input boolean value nextByte() ➺ To input integer value nextShort() ➺ To input integer value nextInt() ➺ To input integer value nextLong() ➺ To input integer value nextFloat() ➺ To input floating value nextDouble() ➺ To input floating value next() ➺ To input string i.e. space is delimiter here nextLine() ➺ To input string i.e. enter is delimiter here next().charAt(0) ➺ To input a character
import java.util.*;
public class ScannerClass {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the boolean data : ");
boolean x=sc.nextBoolean();
System.out.println("Enter the byte data : ");
byte a=sc.nextByte();
System.out.println("Enter the short data : ");
short b=sc.nextShort();
System.out.println("Enter the int data : ");
int c=sc.nextInt();
System.out.println("Enter the long data : ");
long d=sc.nextLong();
System.out.println("Enter the float data : ");
float e=sc.nextFloat();
System.out.println("Enter the double data : ");
double f=sc.nextDouble();
System.out.println("Enter a word : ");
String g=sc.next();
System.out.println("Enter the char data : ");
char i=sc.next().charAt(0);
System.out.println("-------------------------------");
System.out.println(x);
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
System.out.println(f);
System.out.println(g);
System.out.println(i);
}
}
Enter the boolean data : false Enter the byte data : 93 Enter the short data : 393 Enter the int data : 9484 Enter the long data : 93943034 Enter the float data : 0404.49 Enter the double data : 984.4949 Enter a word : inspire Enter the sentence : Enter the char data : # ------------------------------- false 93 393 9484 93943034 404.49 984.4949 inspire #