Java Scanner Class Tutorial
Scanner Class in Java
Table of Contents
1. Reading Data from Keyboard - System.in
import java.util.Scanner; // import the Scanner class
class Main {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
// String Input
System.out.println("Enter Name");
String name = input.nextLine();
// Numerical Input
System.out.println("Enter Age");
int age = input.nextInt();
System.out.println("Enter Salary");
double salary = input.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Output:
C:\javademo>java Main
Enter Name
John
Enter Age
23
Enter Salary
23000
Name: John
Age: 23
Salary: 23000.0
C:\javademo>
2. Reading Data from - File
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class JavaScannerreadfile {
public static void main(String[] args) {
try (Scanner sc = new Scanner(new File("sample.txt"))) {
while (sc.hasNext()) {
System.out.println(sc.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
sample.txt
The Scanner class is used to get user input, and it is found in the java.util package. To use the Scanner class, create an object of the class.
Output:
C:\javademo>java JavaScannerreadfile
The Scanner class is used to get user input, and it is found in the java.util package. To use the Scanner class, create an object of the class
C:\javademo>
3. Reading Data from - String
import java.util.Scanner;
public class JavaScannerstr {
public static void main(String[] args) {
String str = "Scanner Example";
Scanner sc = new Scanner(str);
System.out.println("String is " + sc.nextLine());
sc.close();
}
}
Output:
C:\javademo>javac JavaScannerstr.java
C:\javademo>java JavaScannerstr
String is Scanner Example
C:\javademo>
Reading Delimiter String in Java
import java.util.Scanner;
public class JavaScannerdelimeter {
public static void main(String[] args) {
String input = "A,B,C,D,E";
try (Scanner s = new Scanner(input).useDelimiter(",")) {
while (s.hasNext()) {
System.out.println(s.next());
}
}
}
}
Methods list available in Scanner class to read data:
nextBoolean() Reads a boolean value from the keyboard.
nextByte() Reads a byte value from the keyboard.
nextDouble() Reads a double value from the keyboard.
nextFloat() Reads a float value from the keyboard.
nextInt() Reads a int value from the keyboard.
nextLine() Reads a String value from the keyboard.
nextLong() Reads a long value from the keyboard.
nextShort() Reads a short value from the keyboard.
Following diagram shows - How Scanner works
Comments
Post a Comment