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

输出

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 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
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

未完待续


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值