Sunday, 10 March 2013

Using Scanner for input in Java


In last few posts we saw various I/O streams. We saw example code for byte stream and character stream.We saw BufferedStream and we even saw how to take input from standard input using BufferedReader.Now lets see how can we use Scanner to take input and understand When and why do we use it?

Why scanning?

       Objects of type scanner are useful for breaking down formatted input into tokens and translating individual tokens according to their data type.By default, a scanner uses white space to separate tokens. (White space characters include blanks, tabs, and line terminators.

   Lets see how Scanner works by taking an example.

Example code

public class ScannerDemonstartor{
    public static void main(String[] args) throws IOException {

        Scanner s = null;

        try {
            s = new Scanner(new BufferedReader(new FileReader("inFile.txt")));

            while (s.hasNext()) {
        } finally {
            if (s != null) {

Code Analysis and Explanation

        As explained earlier Scanner scan word by word, basically part of line separated by a separator(default is a white space). If you want this separator to be your separator they you do something like below - 

s = new Scanner(new BufferedReader(new FileReader("inFile.txt")),"mySeparator");

Remaining structure of code is very much similar to what we have explained  in last few posts.One more thing we use .hasNext() method to check if more tokens exist.

Using scanner to take input from Standard input

                Scanner sc = new Scanner(;
                String readLine = sc.nextLine();
                int readInt = sc.nextInt();
                boolean readChar = sc.nextBoolean();

and so on.....
In this way you can take any data type as input.We would mostly use Scanner class to take standard inputs in all our future code so understand this completely.Do let me know if you have any questions.

Related Links 


No comments:

Post a Comment

t> UA-39527780-1 back to top