本文介绍了从java中的字符串解析负前缀整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我有一个看起来像这个10 -1 30 -2的字符串,我想读取空格之间的数字。我可以使用FOR语句和代码

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));

Integer.parseInt(myString);

但是当我尝试读取-1的负数时我遇到了问题,我收到了错误消息:

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 ??

推荐答案

您正在尝试解析单个字符' - ')(在将其转换为字符串后,无可否认)而不是字符串-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 use charAt 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.

这篇关于从java中的字符串解析负前缀整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 04:18
查看更多