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 summary: I would be careful as to what code you copy. It is possible you are copying code which happens to work, rather than well chosen code.
In intnumber, parseInt is used and in floatnumber valueOf is used why so?
There is no good reason I can see. It's an inconsistent use of the APIs as you suspect.
Java is case sensitive, and there isn't any Readline()
method. Perhaps you mean readLine().
DataInputStream.readLine() is deprecated in favour of using BufferedReader.readLine();
However, for your case, I would use the Scanner class.
Scanner sc = new Scanner(System.in);
int intNum = sc.nextInt();
float floatNum = sc.nextFloat();
If you want to know what a class does I suggest you have a quick look at the Javadoc.
This will explain it, I think...
import java.io.*;
class reading
{
public static void main(String args[]) throws IOException
{
float number;
System.out.println("Enter a number");
try
{
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
String a = br.readLine();
number = Float.valueOf(a);
int x = (int)number;
System.out.println("Your input=" + number);
System.out.println("Your input in integer terms is = " + x);
}
catch(Exception e){
}
}
}
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());
A DataInputStream
is just a decorator over an InputStream
(which System.in
is) which allows to read using more convenient methods.
As to the Float.valueOf()
, well, that's curious because Float
has .parseFloat()
as well. Here the code grabs a Float
with .valueOf()
which it turns into the primitive float
type using .floatValue()
, which is unnecessary with Java 1.5+ due to auto unboxing.
And as other answers rightly say, these methods are obsolete anyway.
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);