><FONT color=#f70909>作者:意识 转自<a href="http://www.hackbase.com/" target="_blank" >黑基</A>bbs<a href="http://hackbase.com/News/hk" target="_blank" >原创</A>作品版/ r7 F8 g8 v1 P8 h+ |
>9 M, O/ U8 O9 q0 ~2 a, {
> 先从最简单的char输入开始吧。对于每一个java程序,编译器会自动加载java.lang。这个包中包含了一个键盘输入流System.in(1),我们使用read()方法可以从键盘上读入一个char。<a href="http://hackbase.com/hacker" target="_blank" >代码</A>如下
> 我问用到InputStreamReader类。前面我提到了System,in是一个键盘输入流(说明看我的注解)我们使用这个构造方法 InputStreamReader(InputStream in),<a href="http://hackbase.com/hacker" target="_blank" >代码</A>如下</P>
>InputStreamReader input = new InputStreamReader(System.in)</P>5 f$ t. e5 O3 B
>char inputC= (char)input.read();</P>
>(1)in
>String的输入:- `/ P% P4 Q! o F3 F8 U0 c" `4 L
>上面是对输入时所使用的IO包的基本介绍,在实际中直接使用上面的语句,是无法编译和运行的,因为有异常的存在。(Exception)的存在。异常是一种runtime errors(不懂怎么翻译成中文)比如int a= b/h; 当 h==0时,就是runtime error 。java 中有一个类就是 Exception,用来处理异常的。程序要么在存在可能的异常的情况下运行,用throws 要么用try… catch…来捕捉异常。</P>, F0 d& L/ X! k& G$ z; @0 b
>好了,回到我们的输入上来吧,因为在输入可能没有准备好,比如无法找到键盘。 。所以程序必须使用throws或 try …catch…去捕捉异常,并做出处理方法。 </P>" R, x" Z4 l, k* Y( d
>6 M! R% g3 l/ @& s: w, W7 g/ P+ s# G0 n: W
>import java.io.*;</P>" G, {& b, s% j/ X2 w
>0 ~ L' k+ A2 O5 P2 h
>( `& J- ~; a6 F9 g! q. B
>/ b8 X3 v( `5 k
> while(true){& w3 M! H3 b G# @9 L6 V
> if (input.length()>1) { //catch the too much of the input8 M# ?! j* p( D9 c |# A7 O
lease enter again");
> double data;
> data=Double.parseDouble(input); T6 q. Q) w3 I5 a* z' K3 ~8 o" r
>public static int getInt( ) throws java.io.IOException {</P>+ j, w& N0 }8 f# Y4 y# f" b
> int data;8 P& S; z# z; U% o% t
> data=Integer.parseInt(input);| 欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) | Powered by Discuz! X2.5 |