import java.io.IOException;
class read
{
public static void main(String[] args)throws IOException
{
char c;
System.out.println("输入一个字符");
c=(char)System.in.read();
System.out.println("输入的第1个字符是:"+c);
c=(char)System.in.read();
System.out.println("输入的第2个字符是:"+c);
c=(char)System.in.read();
System.out.println("输入的第3个字符是:"+c);
}
}
在上述程序中,输入数字,一切正常,
为什么把char改成int,然后输入数字,输出就发生错误了呢?
class read
{
public static void main(String[] args)throws IOException
{
char c;
System.out.println("输入一个字符");
c=(char)System.in.read();
System.out.println("输入的第1个字符是:"+c);
c=(char)System.in.read();
System.out.println("输入的第2个字符是:"+c);
c=(char)System.in.read();
System.out.println("输入的第3个字符是:"+c);
}
}
在上述程序中,输入数字,一切正常,
为什么把char改成int,然后输入数字,输出就发生错误了呢?
否则 怎么能 赋值呢?char c;
System.out.println("输入一个字符");
c=(char)System.in.read();
(比如说输入的是10,而得到的是49)
它的类是InputStream类,这个类是IO流最底层的抽象类。
它的操作只针对与字节流,也就是byte。然后就是编码的相关知识了。我们从控制台上输入的其实都是字符,记住计算机看到的都是字符。
那么怎么把它转换成数字,就要看你的程序是怎么编写的了。
谈到字符,那就一定要谈到编码。编码其实就是字符和数字的一个映射关系。
字符就是我们输入的东西。而数字,就是存储在计算机当中的内容。
你在用System.in读取的时候,读到的,其实是数字,也就是该字符的数字编码。
而前面的强制类型转换,会将该数字转换成字符类型的数据,这样,你在System.out.println中
显示的就是字符的内容,而不是它的数字编码。
但是,char改成int之后,那就变了。你读到的是字符的数字编码,显示的也是他的字符编码。使用System.out.println("输入的第1个字符是:"+((char)c)); 显示,也就是说,先将整形数据强制类型转换成字符类型的数据,然后在显示。