Thursday, July 30, 2009

Can someone explain this program,especially the Buffered Reader part and the readline()part?

import java.io.*;


public class Task


{


public void demo()throws IOException


{


BufferedReader S1=new BufferedReader(new InputStreamReader(System.in));


String a;


String b;


System.out.println("Enter your String here");


a=S1.readline();


b=S1.readline();


int c=Integer.parseInt(a);


int d=IntegerparseInt(b);


System.out.println(c);


System.out.println(d);


}


}

Can someone explain this program,especially the Buffered Reader part and the readline()part?
A buffered reader can be used to access external data ... just provides a mechanism to pull the text/data into the running program. In this case you are reading from System.in / 'standard in' which is your keyboard. You could also read data in from a file for example using soemthing similiar called InputFileReader.





So in this case we are watching for data coming in from the keyboard. when text arrives (after you type something) the readline sets 'a' to this value, then the next line sets 'b' to the whatever text you enter next.





The sequence of events are ...





print the line 'Enter your ...'


collects the next 2 things you enter


prints/displays the captured data/text on System.out .. your screen.





To make this work you need to have a JRE loaded on your pc and you must compile this code.... check web for details
Reply:S1 is obviously a "Buffered Reader". Notice it is created from the object System.in which is the keyboard. Buffered readers have lots of nice methods you can call like readline() which returns a line from S1 (which in this case is ultimately the keyboard). Therefore "a" and "b" contain the first two lines that you type after the program begins. Integer.parseInt() tries to convert your two inputs (which are strings now) into ints (which you can do math on).
Reply:This is a simple Java console IO program that prints a prompt to standard out (in this case the screen). In then reads in the next two lines entered on the screen. It will try to parse an integer from the inputed strings, if it can't its going to throw an exception. If it does, it will print the integers it was able to parse out.





BufferedReader S1=new BufferedReader(new InputStreamReader(System.in));





Just wraps the input stream reader with a buffered stream reader. There are advantages to doing this including getting all the methods and properties that a buffered stream reader has.


No comments:

Post a Comment