如何在Java中使用readline()方法? [英] How to use readline() method in Java?
问题描述
我是Java的初学者,我正在阅读通过键盘上的 readLine()
方法为变量赋值的主题。书中给出的程序如下:
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
我想要提出以下问题:
-
在以下声明中做了什么?
What is done in the following statement?
DataInputStream in = new DataInputStream(System.in);
如果中的是<$的对象c $ c> DataInputStream
那么什么是新的以及上述语句右侧的语句有什么作用?
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?
为什么使用不同的方法将整数值放入intnumber并将float值放入floatnumber?
Why have different methods been used for putting the integer value into intnumber and float value into floatnumber?
推荐答案
我建议您使用 Scanner
而不是 DataInputStream
。 扫描程序
专为此目的而设计,并在Java 5中引入。请参阅以下链接以了解如何使用扫描程序
。
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
.
- Java Documentation
- Java Tutorial
示例
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());
这篇关于如何在Java中使用readline()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!