System.in.read()可以实现输入字符,返回字符的Unicode码,但是缺点是只能输入一个字符,如
public class exec
{
public static void main( String args[] ) throws Exception
{
int i=System.in.read();
System.out.println(i);
}
}
如果输入1
输出为49
如果输入123
输出还是49
利用System.in.read()的重载函数可以实现对多个字符的输入,如
public class exec
{
public static void main( String args[] ) throws Exception
{
byte[] barray=new byte[5];
System.in.read(barray);
for(int i=0;i<barray.length;i++)
System.out.println(barray[i]);
}
}
如果输入1
输出为
49
13
10
0
0
如果输入12
输出为
49
50
13
10
0
此时可以发现输入的还是Unicode码,但是会多产生很多其他字符,如回车和换行等。
如何进一步将字节数组信息转换成所需类型,可以使用字符串类来进行,如:
import java.sql.*;
public class exec
{
public static void main(String [] args)throws Exception
{
byte[] b=new byte[10];
System.in.read(b);
String s=new String(b);
System.out.println(s);
}
}
更好的做法是使用流类进行处理输入
[此贴子已经被作者于2010-12-12 07:36:00编辑过]