Scanner class in java
In previous post , we have see Console class in java. In this post, we will see usage of Scanner class.
In java, Scanner class is used to read the input from keyboard. Even though, there are numerous ways to read the keyboard input, Scanner is one of them.
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace bydefault. It provides many methods to read and parse various primitive values.The resulting tokens may then be converted into values of different types using the various next methods
It can parse primitive types and strings using regular expressions.It implements Iterator and closeable Interfaces.
Few Constructors Of scanner class:
- Scanner(File source): Constructs a new Scanner that produces values scanned from the specified file.
- Scanner(File source, String charsetName): Constructs a new Scanner that produces values scanned from the specified file.
- Scanner(InputStream source): Constructs a new Scanner that produces values scanned from the specified input stream.
- Scanner(InputStream source, String charsetName): Constructs a new Scanner that produces values scanned from the specified input stream.
- Scanner(String source): Constructs a new Scanner that produces values scanned from the specified string.
Commonly used methods of Scanner class:
Methods | Description |
public String next() | It returns the next token from the scanner. |
public String nextLine() | it moves the scanner position to the next line and returns the value as a string. |
public byte nextByte() | it scans the next token as a byte. |
public short nextShort() | it scans the next token as a short value. |
public int nextInt() | it scans the next token as an int value. |
public long nextLong() | it scans the next token as a long value. |
public float nextFloat() | it scans the next token as a float value. |
public double nextDouble() | it scans the next token as a double value. |
Example of Scanner class:
public class SacnnerEx { public static void main(String[] args){ Scanner sc=new Scanner(System.in); System.out.println("Enter your Empid"); int rollno=sc.nextInt(); System.out.println("Enter your name"); String name=sc.next(); System.out.println("Enter your Salary"); double fee=sc.nextDouble(); System.out.println("EmpID:"+rollno+" name:"+name+" Salary:"+fee); sc.close(); } }
Enter your Empid 1234
Enter your name ABC
Enter your Salary 10000
EmpID:1234 name:ABC Salary:10000.0