在我的Java程序中,我通过串口从我的Arduino接收到一个字符串。
该字符串存储在变量(字符串):结果中。整数到字符串问题
什么样的数据可以是一个例子:“W:125”(总是1个字符,一个冒号和一个空格,从我的Arduino一个模拟值)
在我的代码我做的:
int spacePos = result.indexOf(" "); // search where the space is
number= result.substring(spacePos+1); // take everything what comes behind the space
System.out.println(number); // print the value, example : 125
int number2 = Integer.parseInt(number);// this should convert the String 125 to a integer with value 125
System.out.println(number2);// should print a integer with value 125
带子串的部分工作;我认为。当我打印数字时,我可以在NetBeans的输出屏幕中看到125,但是我可以选择几个空格?在我的号码后面。
但是当我打印number2时,我什么都看不到。
您可能提供的任何帮助表示赞赏。谢谢。
它抛出任何异常吗? – PermGenError 2013-02-12 16:26:58
try number.trim() – BobTheBuilder 2013-02-12 16:28:12
'number'的长度是多少?是否在'125“后有一些意想不到的字符会抛弃分析器?你可以在解析之前修剪字符串吗? – Floris 2013-02-12 16:29:18