Parse a negative prefix integer from string in java

别等时光非礼了梦想. 提交于 2019-12-31 04:02:58

问题


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


回答1:


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.




回答2:


Is this what you want?

for (String number : "10 -1 30 -2".split("\\s"))
{
    int x = Integer.parseInt(number);
    System.out.println(x);
}

This will print:

10
-1
30
-2



回答3:


Maybe you want to use a StringTokenizer to split the String at certain characters.

StringTokenizer st = new StringTokenizer("10 -1 30 -2");
while (st.hasMoreTokens()) {
  String intStr = st.nextToken();
  int x = Integer.parseInt(intStr);
  System.out.println(x);
}


来源:https://stackoverflow.com/questions/7360111/parse-a-negative-prefix-integer-from-string-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!