Tag Archives: Scanner

[Solved] java.util.InputMismatchException


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.

[Solved] java.util.NoSuchElementException


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().

Java : Convert Decimal to Binary


In this blog, you will learn to convert decimal number into binary string. The java.lang package provides api’s to convert a decimal number into a binary number.

Example
This program takes a decimal number from user as string and convert it to decimal number. toBinaryString() method takes an integer type value and returns its string representation of integer values which represents the data in binary. The base of binary number is 2.

import java.util.Scanner;

public class ConvertDecimalToBinary {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

System.out.println("Enter the decimal value:");
String hex = scan.nextLine();
// convert String to Int
int i = Integer.parseInt(hex);
// convert integer to binary
String by = Integer.toBinaryString(i);
// print binary String
System.out.println("Binary: " + by);
}
}

Output


Enter the decimal value:
12
Binary: 1100

Enter the decimal value:
200
Binary: 11001000

Java :Different ways of Reading a text file


There are multiple ways of reading a text file in Java as below:

  1. BufferedReader
  2. FileReader
  3. Scanner
  4. Stream/Files (java 8): Read all file lines
  5. Paths (Java 8) : Read text file as String

Every way have something different as BufferedReader provides buffering of data for fast reading and Scanner provides parsing ability while we can use both BufferedReader and Scanner to read a text file line by line in Java.

Java 8 introduced Stream class java.util.stream which provides a lazy and more efficient way to read a file.

File Reading By BufferedReader

This method reads text from a character-input stream. It does buffering for efficient reading of characters, arrays, and lines.The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,


BufferedReader in = new BufferedReader(Reader in, int size);
try {
    File file = new File(FILE);
    BufferedReader br = new BufferedReader(new FileReader(file));
    String st;
    while ((st = br.readLine()) != null)
	System.out.println(st);
} catch (IOException ex) {
	ex.printStackTrace();
}

Note : In below code examples not follow usual practices of writing good code like flushing/closing streams, Exception-Handling etc, to reduce number of lines code for better understanding.

File Reading By FileReader

FileReader is convenient class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.


Constructors defined in this class are:
FileReader(File file) : Creates a new FileReader, given the File to read from.

FileReader(FileDescriptor fd): Creates a new FileReader, given the FileDescriptor to read from.

FileReader(String fileName): Creates a new FileReader, given the name of the file to read from.
try {
     FileReader fr = new FileReader(FILE);

     int i;
     while ((i = fr.read()) != -1)
	System.out.print((char) i);
} catch (IOException ex) {
	ex.printStackTrace();
}

File Reading By Scanner

A scanner can parse primitive types and strings using regular expressions and breaks its input into tokens using a delimiter pattern, which by default matches white space. The resulting tokens may then be converted into values of different types using the various next methods.

try {
	File file = new File(FILE);
	Scanner sc = new Scanner(file);

	while (sc.hasNextLine())
	System.out.println(sc.nextLine());
	} catch (Exception ex) {
	ex.printStackTrace();
	}

Read file by scanner without loop

File file = new File(FILE);
try {
	Scanner sc = new Scanner(file);
	// Use delimiter \Z for next line
	sc.useDelimiter("\Z");

	System.out.println(sc.next());
} catch (Exception ex) {
	ex.printStackTrace();
}

File Reading By Stream (Java8)

Files.readAllLines() method read all lines from a file and ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.
Bytes from the file are decoded into characters using the specified charset.


public static List readAllLines(Path path,Charset cs)throws IOException

This method recognizes the following as line terminators:
CARRIAGE RETURN followed by LINE FEED (u000D followed by u000A)
u000A, LINE FEED
u000D, CARRIAGE RETURN
List<String> lines = Collections.emptyList();
		try {
			lines = Files.readAllLines(Paths.get(FILE), StandardCharsets.UTF_8);
			Iterator<String> itr = lines.iterator();
			while (itr.hasNext())
				System.out.println(itr.next());
		} catch (IOException e) {
			e.printStackTrace();
		}

File Reading By Paths (Java8)

try {
			String data = new String(Files.readAllBytes(Paths.get(FILE)));
			System.out.println(data);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

Complete Example

In below example  covered all the above cases.

Test Data


Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
package com.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class FileReadingWay {
	private static final String FILE = "C:\Users\saurabh.gupta1\Desktop\Test Data.java";

	public static void main(String[] args) {
		FileReadingWay s = new FileReadingWay();
		System.out.println("===============Read File By Buffered Reader================");
		s.readFileByBufferedReader();
		System.out.println("===============Read File By File Reader================");
		s.readFileByFileReader();
		System.out.println("===============Read File By Scanner================");
		s.readFileByScanner();
		System.out.println("===============Read File By Scanner without Loop================");
		s.readFileByScannerWithOutLoop();
		System.out.println("===============Read All Files================");
		s.readFileByReadAllFiles();
		System.out.println("===============Read Text File and String================");
		s.readTextFileAsString();
	}

	private void readFileByBufferedReader() {
		try {
			File file = new File(FILE);

			BufferedReader br = new BufferedReader(new FileReader(file));

			String st;
			while ((st = br.readLine()) != null)
				System.out.println(st);
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	private void readFileByFileReader() {
		System.out.println();
		try {
			FileReader fr = new FileReader(FILE);

			int i;
			while ((i = fr.read()) != -1)
				System.out.print((char) i);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		System.out.println();
	}

	private void readFileByScanner() {

		try {
			File file = new File(FILE);
			Scanner sc = new Scanner(file);

			while (sc.hasNextLine())
				System.out.println(sc.nextLine());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void readFileByScannerWithOutLoop() {
		File file = new File(FILE);
		try {
			Scanner sc = new Scanner(file);
			// Use delimiter \Z for next line
			sc.useDelimiter("\Z");

			System.out.println(sc.next());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void readFileByReadAllFiles() {
		List<String> lines = Collections.emptyList();
		try {
			lines = Files.readAllLines(Paths.get(FILE), StandardCharsets.UTF_8);
			Iterator<String> itr = lines.iterator();
			while (itr.hasNext())
				System.out.println(itr.next());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void readTextFileAsString() {
		try {
			String data = new String(Files.readAllBytes(Paths.get(FILE)));
			System.out.println(data);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}

Output


===============Read File By Buffered Reader================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read File By File Reader================

Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read File By Scanner================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read File By Scanner without Loop================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read All Files================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read Text File and String================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 

References

 

[Solved]java.util.NoSuchElementException


java.util.NoSuchElementException is runtime unchecked exception which throws by  nextElement() method of an Enumeration or nextXYZ() method of Scanner to indicate that there are no more elements in the enumeration or scanner.

Constructors

  • NoSuchElementException() : Constructs a NoSuchElementException with null as its error message string.
  • NoSuchElementException(String s) : Constructs a NoSuchElementException, saving a reference to the error message string s for later retrieval by the getMessage() method.

Example  NoSuchElementException

In below example NoSuchElementException occured because using useDelimiters(“\sGaurav\s“) while in test input using delimiters as “Saurabh”. In that case scanner will have only one text line and not split. When we retrieve data from scanner will throw this NoSuchElementException.

import java.util.Scanner;
public class JavaScannerParsingExample {
	public static void main(String[] args) {
		String input = "Facing Saurabh Issues Saurabh On Saurabh IT Saurabh 123 Saurabh 54 Saurabh";
	     Scanner s = new Scanner(input).useDelimiter("\s*Gaurav\s*");
	     System.out.println(s.next());
	     System.out.println(s.next());
	     System.out.println(s.next());
	     System.out.println(s.next());
	     System.out.println(s.nextInt());
	     System.out.println(s.nextInt());
	     s.close();
	}
}

Output

Facing Saurabh Issues Saurabh On Saurabh IT Saurabh 123 Saurabh 54 Saurabh
Exception in thread "main" java.util.NoSuchElementException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at com.userinput.JavaScannerParsingExample.main(JavaScannerParsingExample.java:11)

Solutions

  • In case of enumeration always check for hasNextElement() before use method next() to retrieve element of enumeration.
  • In case of Scanner always check for hasNext() before use method nextXYZ() to retrieve values from scanner.

References

https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s