Monday, July 22, 2013

Reading from Console: JAVA Scanner vs BufferedReader

When read an input from console, there are two options exists to achive that. First using Scanner, last using BufferedReader. Both of them have different characteristics. It means differences how to use it.
Scanner treated given input as token. BufferedReader just read line by line given input as string. Scanner it self provide parsing capabilities just like nextInt(), nextFloat().
But, what is others differences between?
  1. Scanner treated given input as token. BufferedReader as stream line/String
  2. Scanner tokenized given input using regex. Using BufferedReader must write extra code
  3. BufferedReader faster than Scanner *point no. 2
  4. Scanner isn’t synchronized, BufferedReader synchronized
Scanner come with since JDK version 1.5 higher.
When should use Scanner, or Buffered Reader?
Look at the main differences between both of them, one using tokenized, others using stream line. When you need parsing capabilities, use Scanner instead. But, i am more comfortable with BufferedReader. When you need to read from a File, use BufferedReader, because it’s use buffer when read a file. Or you can use BufferedReader as input to Scanner.

Read input from console using JAVA Scanner and BufferedReader Library

Scanner
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
 
/**
 * @author CodeLover
 */
public class Console {
     
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String name;
        List<String> hobbies = new ArrayList<String>();
        int age;
        String choice;
         
        // INPUT
        System.out.print("Enter your name: "); name = scan.nextLine();
        System.out.print("Now, enter your age below:"); age = scan.nextInt();scan.nextLine();
        System.out.print("What is your hobbies (separated by comma): ");
        String temp = scan.nextLine();
        // process entered hobby
        Scanner scanHobby = new Scanner(temp);
        scanHobby.useDelimiter(",");
        while (scanHobby.hasNext()) {
            hobbies.add(scanHobby.next().trim());
        }
         
        // OUTPUT
        System.out.print("\n\nYou've just entered '" + name + "' as your name.\n");
        System.out.println("Your age is " + age + " years old");
        System.out.println("Your hobbies are");
        for (String hobby : hobbies) {
            System.out.println("-" + hobby);
        }
        do {
            System.out.print("Is that correct? (Y/N) : ");
            choice = scan.nextLine();
            if (!choice.equals("Y") && !choice.equals("N")) {
                System.out.println("Please choose Y or N");
            }
        } while (!choice.equals("Y") && !choice.equals("N"));
        if (choice.equals("Y")) {
            System.out.println("\nThanks for submitting!");
        } else {
            System.out.println("\nYou've cancelled submitting");
        }
    }
}
If you notice, you will wonder what this line suppose to do:
19
System.out.print("Now, enter your age below:"); age = scan.nextInt();scan.nextLine();
Scanner will tokenize all input. NextLine() method will consume until line feed found. Others method like nextInt(), nextFloat() or simply next() will consume next token parsed by existing delimiter.
When you enter: 45 35 65 45
first call nextInt() will get ’45′
nextLine() will get remaining line ’35 65 45′ without provide System halt
When nextInt(), nextLine() or thers ‘next’ method was called, i discover it will lookup to it’s buffer. If there no buffer/token, than it do System halt to get input from user.
BufferedReader
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
/**
 *
 * @author CodeLover
 */
public class Console {
     
    public static void main(String[] args) {
        BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
        String name;
        String hobbies[];
        int age;
        String choice;
         
        try {
            // INPUT
            System.out.print("Enter your name: "); name = scan.readLine();
            System.out.print("Now, enter your age below:"); age = Integer.parseInt(scan.readLine());
            System.out.print("What is your hobbies (separated by comma): ");
            hobbies = scan.readLine().split(",");
 
            // OUTPUT
            System.out.print("\n\nYou've just entered '" + name + "' as your name.\n");
            System.out.println("Your age is " + age + " years old");
            System.out.println("Your hobbies are");
            for (String hobby : hobbies) {
                System.out.println("-" + hobby.trim());
            }
            do {
                System.out.print("Is that correct? (Y/N) : ");
                choice = scan.readLine();
                if (!choice.equals("Y") &amp;&amp; !choice.equals("N")) {
                    System.out.println("Please choose Y or N");
                }
            } while (!choice.equals("Y") &amp;&amp; !choice.equals("N"));
            if (choice.equals("Y")) {
                System.out.println("\nThanks for submitting!");
            } else {
                System.out.println("\nYou've cancelled submitting");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment