[java] “Why this blank Scanner sh*t after each time of taking int or double as input?”

Well, by using java.util.Scanner we can take input from the user, it can be String, it can be integer, it can be double, even it can be a line!

to use java util.Scanner, we first import java.util.* package, then we declare an object of Scanner class:

Scanner sc = new Scanner (System.in);

Since System.in is an input stream, above declared Scanner will takes all necessary inputs from its input streams and System.in let the user give input streams through the system (maybe keyboard).

Various types of inputs can be taken as i have mentioned, can be taken via various next methods:

For example:

next() method is used to take input a word, it starts taking input from the streams and does not not stop until it spots character  a ‘ ‘ (space)!

Example: if the given input of the user is: “yo man”
then next() method will return “yo “, cause, after yo it spots a space ” ” and it refrains from taking any other inputs but in input stream still it has “man”  left next to “yo “, so if we again let next() method get called, then as input stream already has streams, so that next() won’t ask the user to give another input but it would take from the next input stream and so it would return “man” !

nextLine() takes input from the user until it reach an Enter. We have learned that <Enter> is nothing but a spacial character.

Example: users given input is: “yo man” and then press Enter
“How are you” and then press Enter
then nextLine() method will only return “yo man”, cause, after “yo man” it spotted an <Enter> and it refrains from taking any other inputs but in its input stream “How are you <Enter>” is still left!

nextInt() method takes integer inputs from the use and suppose now we call nextInt() method then it will start taking inputs from input stream which was left  before (i mean “How are you <Enter>”) and it would fail to get an Integer so
java.util.InputMismatchException will get thrown.

Now we will see a practical problem that we face due to this sort of thing:

import java.util.*;
public class Student{
Scanner sc=new Scanner(System.in);
System.out.print("Serial no: ");
int Serial =sc.nextInt(); //1st input from the user
System.out.print("Name: ");
String Name = sc.nextLine(); //won't ask the user to give an input
}
}

Why? Why? Why?
At the time when user gives an Integer when “Serial no: ” is asked, the user presses an integer number and then <Enter>.
nextInt() method returns that number and int Serial variable stores that intiger with no difficulty but in input stream <Enter> remains so at the time when nextLine() is being called (at the time when user is asked to give the “Name: ” ) it takes that <Enter> as a input from the input stream so user does not get any chance to enter the name.

Giving a blank sc.nextLine() after each sc.nextInt() can be a solution for this problem as String can hold anything.

System.out.print("Serial no: ");
int Serial =sc.nextInt(); /*user inputs a number and then presses <Enter> and int Serial stores only the number not that extra <Enter>*/
sc.nextLine(); /* it takes extra <Enter> */
System.out.print("Name: ");
String Name = sc.nextLine();

I think this blog post could be dedicated to a Friend with “Whys”, Fahim Bakhtiar, unlike any element of my so called GoodStudent class 😛 who has an unlimited amount of Wh-Questions to ask in his mind. And most probably I also fear what he would ask again regarding this issue where i will get stumbled miserably 😛 but he is always welcome as always! All the best to him!

Disclaimer: This is what i have assumed about Scanner class. Correct me if i am wrong! Suggest me good articles about this Scanner as i have got nothing.

[java] FileInputStream and Reading line by line:

The computer that we are using right now is digital electronic, it is digital because all the information inside it is represented by streams of numbers, more specifically binary numbers. From the perspective of Computer every single file is nothing but a stream of binary numbers. Still now sometimes i stare at my computer and think what not we are making it to do so but it knows nothing more than 0 and 1?  WTF! (Well, That’s Fantastic!)

Before dealing with FileInputStream first of all we have to know what FileInputStream really is.

FileInputIstream is basically a child class of InputStream. It obtains input bytes from a file in a file system. Stream classes basically deal with binary datas and in binary there is no such thing as a “line” so FileInputStream does not have any method which is related with lines.

Our objective is to read from a file line by line using FileInputStream.

First of all it’s in a different not included in java.lang package so if we will use FileInputStream we need to import java.io.* at the beginning of the class.

Scanner or BufferedReader has methods to work with lines so if we can can somehow scan/read Streams through Scanneror BufferedReader, then we can read them line by line using nextLine() or readLine() method.

Constructor Summary of Scanner
Scanner(InputStream source)
Constructs a new Scanner that produces values scanned from the specified input stream.
more…

Scanner does give us opportunity to pass a InputStream through its constructor.

Now, we need to think of a way to make an connection our given file and java.

Constructor of  FileInputStream 
FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.

 throws FileNotFoundException
FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

throws FileNotFoundException

From the summary of the constructor of FileInputStream, we can easily guess  at least two way to make this linkage through the constractor:

1. FileInputStream(String name)
2. FileInputStream(File file)

1. FileInputStream(String name): i think this is the most straight forward way to do this thing. If the file we want to read and our file which we want to to read line by line are at the same directory then we can just write that files name and extension as name constractor and as this constractor throws FileNotFoundException so we also need to handle that exception.

Example: if we want to read a file named “sample.txt” then we would write:

try{
FileInputStream fileInStreamObj = new FileInputStream("sample.txt" );
}
catch (FileNotFoundException e){
System.out.println(e);

But if file which we want to to read line by line are not at the same directory then we have to write that files directory briefly and we have to use double ‘//’ in place of single ‘/’ (FYI: as ‘/’ is a escape character and you can’t store a single ‘/’ in a character veritable). Example: if we want to read a file named “sample.txt” which is located at the directory of “C:\Documents and Settings\User\Desktop\sample.txt”, then you have to write:

FileInputStream fileInStreamObj = new FileInputStream("C:\\Documents and Settings\\User\\Desktop\\sample.txt" );

try blocks confines the scope of variables, so we can put this previous piece of code inside same try  block.

Combinig all the pieces:

import java.io.*;
import java.util.Scanner;
public class ReadALineUsingFileInputStream {
public static void main (String [] args){
try{
FileInputStream fileInStreamObj = new FileInputStream("sample.txt" );
InputStream inStreamObject = ((InputStream) fileInStreamObj);
Scanner sc = new Scanner( inStreamObject );
String input = sc.nextLine();
System.out.println(input);
}
catch (FileNotFoundException e){
System.out.println(e);
}
}
}

2. FileInputStream(File file): If we want to use this contractor, first of all we need to define file location with an object of File and then let it go through with FileInputStreams constractor and this constractor also throws FileNotFoundException so we also need to handle that exception.:

try{
File fileObject = new File("sample.txt" );
FileInputStream fileInStreamObj = new FileInputStream(fileObject);
}
catch (FileNotFoundException e){
System.out.println(e);
}

Now we need to convert this FileInputStream into InputStream, but they are  in the same tree so we can cast them. So here we go:


InputStream inStreamObject = (InputStream) fileInStreamObj
Scanner sc = new Scanner(  inStreamObject );
String input = sc.nextLine();

combining all peaces:

import java.io.*;
import java.util.Scanner;
public class ReadALineUsingFileInputStream {
public static void main (String [] args){
try{
File fileObject = new File("sample.txt" );
FileInputStream fileInStreamObj = new FileInputStream(fileObject);
InputStream inStreamObject = (InputStream) fileInStreamObj;
Scanner sc = new Scanner( inStreamObject );
String input = sc.nextLine();
System.out.println(input);
}
catch (FileNotFoundException e){
System.out.println(e);
}
}
}



we can also do similar thing using BufferedReader:

Constructor Summary of BufferedReader
BufferedReader(Reader in)
Create a buffering character-input stream that uses a default-sized input buffer.
more…

So BufferedReader can take Reader as constructor.

Now we have to convert FileInputStream into Reader or any of its child class.

Constructor Summary of InputStreamReader extends Reader
InputStreamReader(InputStream in)
Create an InputStreamReader that uses the default charset.
more…

InputStreamReader can take  FileInputStream and its in the the same tree of Reader so we can cast any InputStreamReader object into Reader.
ReadLine() method of BufferedReader throws IOException, so we also need to handle that exception.
so,
try{
InputStreamReader inStreamReaderObject = new InputStreamReader(fileInStreamObj);
BufferedReader br = new BufferedReader( (Reader) inStreamReaderObject );
String input = br.readLine();
}
catch(IOException e){
System.out.println(e);
}

combinig previous pieces:

import java.io.*;
public class ReadALineUsingFileInputStream {
public static void main (String [] args){
try{
FileInputStream fileInStreamObj = new FileInputStream("sample.txt");
try{InputStreamReader inStreamReaderObject = new InputStreamReader(fileInStreamObj);
BufferedReader br = new BufferedReader( (Reader) inStreamReaderObject );
String input = br.readLine();
System.out.println(input);
}
catch(IOException e){
System.out.println(e);
}
}
catch (FileNotFoundException e){
System.out.println(e);
}
}
}

Hurrah, now we know how to read a line using FileInputStream. Now using a loop until Scanner hasNext()  or BufferedReader’s readLine() method returns a null!