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

来源:互联网 发布:大学生java实训学校 编辑:程序博客网 时间:2024/05/17 04:55

输出

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

println() 加上回车换行

输入

1. BufferedReader

01// MAKE SURE TO IMPORT java.io.*!!!!
02import java.io.*;
03 
04public 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 String to 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
02import java.util.Scanner;
03 
04public 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

未完待续


原创粉丝点击