简体   繁体   English

char (int) 和 int 之间的区别

[英]Difference between char (int) and int

I have a piece of code, that receives values from a sensor (Via serialport using rxtx) and displays it.我有一段代码,它从传感器接收值(通过使用 rxtx 的串行端口)并显示它。 Strangely, the following code奇怪的是,下面的代码

int value = in.read();
System.out.print((char) value);

Outputs the desired value as:将所需值输出为:

RXTX Warning:  Removing stale lock file. /var/lock/LK.005.018.009
20
27
29
26
21

But when I change the above code as following:但是当我将上面的代码更改如下时:

int value = in.read();
System.out.print("The value is"+(char) value);

The output becomes:输出变为:

RXTX Warning:  Removing stale lock file. /var/lock/LK.005.018.009
The value is2The value is6The value is
The value is2The value is2The value is

As it can be seen, the integer splits.可以看出,整数分裂。 For quite a while, I am unable to figure it out?想了半天,还是想不通?

Is there a way where I can save the console value into an integer, as I would be using this value in the future.有没有办法可以将控制台值保存为整数,因为我将来会使用这个值。

As it can be seen, the integer splits.可以看出,整数分裂。 For quite a while, I am unable to figure it out?想了半天,还是想不通?

You are not reading integers, you are reading bytes which have characters encoded as ?ASCII?您不是在读取整数,而是在读取字符编码为 ?ASCII? 的字节。

Is there a way where I can save the console value into an integer, as I would be using this value in the future?有没有办法可以将控制台值保存为整数,因为我将来会使用这个值?

The simplest way is to use a Scanner最简单的方法是使用扫描仪

Scanner scanner = new Scanner(in);
while (scanner.hasNextInt()) {
   // read bytes up the next whitespace, parse as a int
   int n = scanner.nextInt();

Don't cast it to char.不要将其转换为字符。 Just print只需打印

System.out.print("The value is " + value);

在第二个示例中,您将 int 转换为 char,但是当您将它连接到 string 时,您什么也看不到,因为这些是不可打印的字符。

Your code converted the value number into a character, using Java's UCS2 representation.您的代码使用 Java 的 UCS2 表示将value编号转换为字符。 You may need it only if you want to treat the value as a character data (eg String).仅当您想将值视为字符数据(例如字符串)时才需要它。

If you need it only as an integer value (eg for printing), you don't need to convert.如果您只需要它作为整数值(例如用于打印),则不需要转换。

please check this snippet by adopting to your code请通过采用您的代码来检查此代码段

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));   
   String  line = br.readLine();
   String[] words = line.split("[ ]",0); //white space delimiter
   for(int i = 0; i < words.length; i++) {
   System.out.print("The value is " +words[i]);
   System.out.print("\n");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM