1
import java.io.*;
class Test{
    public static void main(String args[])throws IOException{
        char a[]=new char[4];       
        DataInputStream in=new DataInputStream(System.in);
        for(int i=0;i<4;i++)
            a[i]=in.readChar();
        System.out.println("Characters are : ");
        for(int i=0;i<4;i++)
            System.out.println(a[i]);
    }   
}

输出:

java Test
a
s
d
f
Characters are : 
愊
猊
搊
昊

在这里,我阅读了字符 a、s、d 和 f ..但它打印了一些其他字符..

4

3 回答 3

0

Check this out, this will work,

        char a[]=new char[4];      
        Scanner in =new Scanner(System.in);
        for(int i=0;i<4;i++) {
            a[i]=(char) in.next().charAt(0);
        }
        System.out.println("Characters are : ");
        for(int i=0;i<4;i++) {
            System.out.println(a[i]);
        }

Problem with your code is:

while the input is given, byte format of the input is considered and then Unicode value of byte is stored to a, so you get special characters.

Did not know how to do with DataInputStream so did it with Scanner,

Hope this helps!

于 2013-10-05T17:18:29.160 回答
0

输入字符使用以下逻辑进行操作:

(char)((a << 8) | (b & 0xff))

请参阅readChar文档:

public char readChar() 抛出 IOException

读取输入字符并返回字符值。Unicode 字符由两个字节组成。设 a 为读取的第一个字节, b 为第二个字节。返回的值为: (char)((a << 8) | (b & 0xff))

该方法适用于读取接口DataOutput的writeChar方法写入的字节。

于 2013-10-05T17:07:37.707 回答
0

如果您只想读取字符,则可以使用更好的选择BufferedReader

您可以使用public static BufferedReader newBufferedReader(Path path, Charset cs)该类Files来获得一个BufferedReader. 除了支持字符集之外,它还非常高效,因为它可以缓冲数据 :)

于 2013-10-05T17:01:54.003 回答