I have a piece of code, that receives values from a sensor (Via serialport using rxtx) and displays it. 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?
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. 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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.