输出
print() 输出对象的toString()方法的内容
println() 加上回车换行
输入
1. BufferedReader
01 |
//
MAKE SURE TO IMPORT java.io.*!!!! |
06 |
public
static void main(String[] args) |
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); |
12 |
//
use the InputStreamReader as the parameter to read from
keyboard |
13 |
BufferedReader
reader = new BufferedReader(rdr); |
15 |
//
prompt for what
to enter |
16 |
System.out.print("Enter
a number: "); |
18 |
//
get the input (ALWAYS A STRING) |
19 |
String in =
reader.readLine(); |
21 |
//
transfer that String to an integer |
22 |
int
number = Integer.parseInt(in); |
25 |
System.out.println(number); |
BufferReader的缺陷
输入数据的类型总是String,需要将String对象解析为整型或者其他类型的数据。而且它允许你输入任何内容,
在运行时可能产生错误或异常。
2. Scanner (JDK 1.5版本以上)
支持多数据类型的输入,易于使用。
01 |
//
does NOT use java.io |
02 |
import java.util.Scanner; |
06 |
public
static void main(String[] args) |
08 |
//
much easier declaration |
09 |
Scanner
scan = new Scanner(System.in); |
12 |
System.out.print("Enter
a number: "); |
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(); |
21 |
System.out.println(number); |
3. Console
未完待续