从java中的字符串中解析负前缀整数
嗨,我有一个看起来像这样的字符串 10 -1 30 -2,我想读取空格之间的数字。我可以使用 FOR 语句和代码来做到这一点
Character.toString(myString.charAt(i));
,但是
Integer.parseInt(myString);
当我尝试读取像 -1 这样的负数时,我遇到了一个问题,并且收到了错误消息:
09-09 13:06:49.630: ERROR/AndroidRuntime(3365): Caused by: java.lang.NumberFormatException: unable to parse '-' as integer
有什么想法如何解决这个问题吗?
Hi i have a string looking something like this 10 -1 30 -2 and i want to read the numbers between spaces. I can do this using a FOR statement and the code
Character.toString(myString.charAt(i));
and
Integer.parseInt(myString);
But i face a problem when i try to read negative number like -1 and i got the error message:
09-09 13:06:49.630: ERROR/AndroidRuntime(3365): Caused by: java.lang.NumberFormatException: unable to parse '-' as integer
Any ideas how to solve this ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是你想要的吗?
这将打印:
Is this what you want?
This will print:
您正在尝试解析单个字符 (
'-'
)(无可否认,在将其转换为字符串之后)而不是字符串“-1”。如果您使用charAt
,您将一次解析一个数字,因此“10”将显示为 1,然后是 0,而不是 10。如果您只是拆分您的字符串包含空格,您应该能够毫无问题地解析字符串。
You're trying to parse a single character (
'-'
) (after converting it to a string, admittedly) instead of the string "-1". If you usecharAt
you'll be parsing a single digit at a time, so "10" will come out as 1 and then 0, not 10.If you just split your string on spaces, you should be able to parse the strings with no problems.
也许您想使用 StringTokenizer 在某些字符处分割字符串。
Maybe you want to use a StringTokenizer to split the String at certain characters.