Pre-requisite : Java : Scanner : User input, Parsing and File Reading
Below scanner file reading example throwing “java.util.InputMismatchException” because using scanner.next(regex) but some words in test data not matching regex “\W” for word as in “Sr. project Lead” in given example.
Test data in file
Saurabh Gupta 36 "Sr project Lead" Noida
Sailesh
Nagar 34 "Project Lead"
Example
package scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerToReadInputFromFile {
public static void main(String[] args) {
try {
// Decalare Scanner and intialize with File input object
Scanner sc = new Scanner(
new File("C:\\Users\\Saurabh Gupta\\Desktop\\Data.txt"));
while (sc.hasNextLine()) {
//System.out.println(sc.next(Pattern.compile("\\w+")));
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
Output
Saurabh
Gupta
36
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at scanner.ScannerToReadInputFromFile.main(ScannerToReadInputFromFile.java:17)
Solution
Always handle exception while using regular expressions. In this example pattern is not matching for ‘Sr Project Lead’ because word pattern allow on [A-Za-z0-1] char only.
Like this:
Like Loading...
Pre-requisite : Java : Scanner : User input, Parsing and File Reading
Below scanner file reading example throwing “java.util.NoSuchElementException” because using scanner.next() two times without checking existence of element in file for second scanner.next() element.
Test data in file
Saurabh Gupta 36 "Sr project Lead" Noida
Sailesh
Nagar 34 "Project Lead"
Example
package scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerToReadInputFromFile {
public static void main(String[] args) {
try {
// Decalare Scanner and intialize with File input object
Scanner sc = new Scanner(
new File("C:\\Users\\Saurabh Gupta\\Desktop\\Data.txt"));
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
System.out.println(sc.next());
//System.out.println(sc.next(Pattern.compile("\\w+")));
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
Output
Saurabh Gupta 36 "Sr project Lead" Noida
Sailesh
Nagar
34 "Project Lead"
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at scanner.ScannerToReadInputFromFile.main(ScannerToReadInputFromFile.java:15)
Solution
Always use scanner.next() after checking scanner.hasNext()condition. If scanner.hasNext() returning true then only call scanner.next().
Like this:
Like Loading...
“Learn From Others Experience"