您的位置:首页 > 编程语言 > Java开发

Java Console I/O Java控制台输入与输出

2012-12-30 18:57 483 查看
输出

print() 输出对象的toString()方法的内容

println() 加上回车换行

输入

1. BufferedReader

01
//
MAKE SURE TO IMPORT java.io.*!!!!
02
import
java.io.*;
03
04
public
class
test
05
{
06
public
static void main(String[] args)
07
{
08
//
this line is not necessary, but most people use it
09
//
System.
in
is
the keyboard input stream
10
InputStreamReader
rdr = new InputStreamReader(System.
in
);
11
12
//
use the InputStreamReader as the parameter to
read
from
keyboard
13
BufferedReader
reader = new BufferedReader(rdr);
14
15
//
prompt
for
what
to enter
16
System.out.print(
"Enter
a number: "
);
17
18
//
get the input (ALWAYS A STRING)
19
String
in
=
reader.readLine();
20
21
//
transfer that Stringto an integer
22
int
number = Integer.parseInt(
in
);
23
24
//
output the number
25
System.out.println(number);
26
}
27
}
BufferReader的缺陷

输入数据的类型总是String,需要将String对象解析为整型或者其他类型的数据。而且它允许你输入任何内容,
在运行时可能产生错误或异常。

2. Scanner (JDK 1.5版本以上)

支持多数据类型的输入,易于使用。

01
//
does NOT use java.io
02
import
java.util.Scanner;
03
04
public
class
test
05
{
06
public
static void main(String[] args)
07
{
08
//
much easier declaration
09
Scanner
scan = new Scanner(System.
in
);
10
11
//
prompt
for
input
12
System.out.print(
"Enter
a number: "
);
13
14
//
get the input, NO PARSING.
15
//
The nextInt() method prevents the user
16
//
from crashing the program here...
17
//
As it only accepts number(s) as input
18
int
number = scan.nextInt();
19
20
//
output the number
21
System.out.println(number);
22
}
23
}
3. Console

未完待续
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息