I am beginner in Java, and I was reading the topic of giving values to variables through the readLine()
method from the keyboard. The program for that is given in the book is as follows:
import java.io.DataInputStream class Reading { public static void main(String args[]) { DataInputStream in = new DataInputStream(System.in); int intnumber=0; float floatnumber=0.0f; try { system.out.println("enter an integer: "); intnumber = Integer.parseInt(in.readline()); system.out.println("enter a float number: "); floatnumber = Float.valueOf(in.readline()).floatvalue(); } // Rest of code
I want to ask the following questions:
What is done in the following statement?
DataInputStream in = new DataInputStream(System.in);
If in
is an object of DataInputStream
then what is new and what do the statement on the right-hand side of above statement do?
Why have different methods been used for putting the integer value into intnumber and float value into floatnumber?
The readLine() method of Console class in Java is used to read a single line of text from the console. Parameters: This method does not accept any parameter. Return value: This method returns the string containing the line that is read from the console. It returns null if the stream has ended.
The readLine() method of BufferedReader class in Java is used to read one line text at a time. The end of a line is to be understood by '\n' or '\r' or EOF.
The readlines() method returns a list containing each line in the file as a list item.
Java BufferedReader readLine() Method The readLine() method of Java BufferedReader class reads a line of text. The "/n" and "/r" are line termination character which is used to consider a line.
I advise you to go with Scanner
instead of DataInputStream
. Scanner
is specifically designed for this purpose and introduced in Java 5. See the following links to know how to use Scanner
.
Example
Scanner s = new Scanner(System.in); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next());
Use BufferedReader and InputStreamReader classes.
BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in)); String line=buffer.readLine();
Or use java.util.Scanner
class methods.
Scanner scan=new Scanner(System.in);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With