QA's approach 2 Java - Scanner Class Examples

Scanner Class examples


How does a Scanner work?

Basically, a Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace (blanks, tabs, and line terminators). The parsed tokens can be converted into primitive types and Strings using various next methods. Here’s the simplest example of using a Scanner to read an integer number from the user:

Delimiter

Delimiter will be used by scanner object to tokenize string. This is helpful if we are using Scanner to split String into multiple tokens

usedelimiter(String pattern) method sets the delimiter of this Scanner object

This method is necessary specially in dealing with files as a data source

Important Methods in Scanner class:

next() - to iterate to the next token

hasNext() - return true if next token exists

hasNext(String p) - return true if next token exists 

Example - Reading User input from Keyboard

package fileHandling;

import java.util.Scanner;

public class ReadUserInput {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);
System.out.println("What's your name?");
String name = scanner.next();
 
System.out.print("How old are you? ");
int age = scanner.nextInt();
scanner.nextLine(); 
System.out.print("How much do you earn per month? ");
float salary = scanner.nextFloat();
scanner.nextLine(); 
 
System.out.format("The Details are as follows: \nName: %s\nAge: %d\nSalary: %.2f", name,age, salary);
 
scanner.close();
}

}

Execute the program:




Example 2: Create a Text file, Write Data to file & then read Data from file using scanner class

package fileHandling;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ReadUserInput {

public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner((System.in));
System.out.println("Please enter the file path");
String path = scanner.next();
System.out.println(path);
File f = new File(path);
if (f.createNewFile())
System.out.println("File Created");
else
System.out.println("File already Created");

/To append content to the end of a file, pass a true to FileWriter

  FileWriter fw = new FileWriter(f, true);

 fw.write(" 10 20 30 40 50");
fw.write(" 60");
scanner = new Scanner(new File(path));
int numberRead;
try {
while (scanner.hasNextInt()) {

numberRead = scanner.nextInt();
System.out.println(numberRead);
}
} catch (Exception e) {
e.getMessage().toString();
}

}
}

Execute the Program 1st time:
Alt+Shift+X, J

output is as follows:

Execute the Program 2nd time:
Alt+Shift+X, J

output is as follows:

Example 3: Create a file, write data to file, count the no lines in the file & then read the data line by line

package fileHandling;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ReadUserInput {

public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner((System.in));
System.out.println("Please enter the file path");
String path = scanner.next();
//// String
//// path="C:\\Users\\user\\workspace\\Newfolder\\fileHandling\\src\\Input.txt";
System.out.println(path);
File f = new File(path);
if (f.createNewFile())
System.out.println("File Created");
else
System.out.println("File already Created");

// Write Data to File & read it line by line & get the count of lines in
// file

FileWriter fw = new FileWriter(f);
fw.write("Hello how are you \n");
fw.write("I am fine, how about you \n");
fw.close();
scanner = new Scanner(new File(path));

List<String> listLines = new ArrayList<>();
int count = 0;
while (scanner.hasNext()) {
String line = scanner.nextLine();
listLines.add(line);
count++;

}
System.out.println("No of lines in the File is:" + count + "\n");
System.out.println(listLines.toString() + ":\n");
scanner.close();

// To print the content Line by Line
System.out.println("Data in the file is as follows:\n");
for (String data : listLines)
System.out.println(data);

}
}

Execute the Program 2nd time:
Alt+Shift+X, J

output is as follows:

Example 4: Regular expressions usage

To get count of words from given string

package fileHandling;

import java.util.Scanner;

public class RegExpression {

public static void main(String[] args) {

int count = 0;
System.out.println("Test Space\t" + "Test Space2\f" + "Test ipace2\r" + "Test Java");
String s = "10 tea 20 Biscuitstea and 3 Cofffee";

// Initialize Scanner object to scan the input string & initialize the string delimiter

Scanner scan = new Scanner(s).useDelimiter("\\s");
                //Scanner sc=new Scanner(s).useDelimiter("[ ]");

// Printing the tokenized Strings

while (scan.hasNext()) {
System.out.println(scan.next().toString());
count++;
}
System.out.println("No of words in the input string is :" + count);
}
}

Execute the Program 2nd time:
Alt+Shift+X, J

output is as follows:



To get count of characters including spaces

package fileHandling;

import java.util.Scanner;

public class RegExpression {

public static void main(String[] args) {

int count = 1;
System.out.println("Test Space\t" + "Test Space2\f" + "Test ipace2\r" + "Test Java");
String s = "10 tea 20 Biscuitstea and 3 Cofffee";

Scanner scan = new Scanner(s).useDelimiter("(.)");

while (scan.hasNext()) {
System.out.println(scan.next().toString());
count++;
}
System.out.println("No of words in the input string is :" + count);
}
}

Similarly some more delimiters:

Tokenize or split using any character
Scanner sc=new Scanner(s).useDelimiter("(.)");

Tokenize or split using Tab space
Scanner sc=new Scanner(s).useDelimiter("[\\t]");

Tokenize or split using Digit
Scanner sc=new Scanner(s).useDelimiter("[\\d]");

Tokenize or split using 2places Digits like 10,20,33 followed by space
Scanner sc=new Scanner(s).useDelimiter("[\\d][\\d][ ]");

Tokenize or split using non Digit
Scanner sc=new Scanner(s).useDelimiter("[^\\d]");

Tokenize or split using non Space
Scanner sc=new Scanner(s).useDelimiter("[^\\s]");

Tokenize or split using word
Scanner sc=new Scanner(s).useDelimiter("[\\w]");

Tokenize or split using non word
Scanner sc=new Scanner(s).useDelimiter("[^\\w]");

Pattern Matching & printing:

import java.util.Scanner;

public class RegExpression {

public static void main(String[] args) {

int count = 0;
String s = "10 tea 20 Biscuitstea and 3 Cofffee";

String pattern = ".*tea.*";
String out;
Scanner scan = new Scanner(s);
while (scan.hasNext()) {
if (scan.hasNext(pattern)) {
out = scan.next(pattern);
count++;
System.out.println(out);
} else
scan.next();
}

}
}

Output:
tea
Biscuitstea

Comments

Popular posts from this blog

QA's approach 2 Java - Understanding Static context

Selenium 4 absolute beginners - How to create Batch execution file

Technologies - Log4J - Create Log4j Configuration File - Where ? How ? What ?