Parse a negative prefix integer from string in java

后端 未结 3 1536
天命终不由人
天命终不由人 2021-01-25 05:50

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

Chara         


        
相关标签:
3条回答
  • 2021-01-25 06:20

    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.

    0 讨论(0)
  • 2021-01-25 06:30

    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);
    }
    
    0 讨论(0)
  • 2021-01-25 06:34

    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
    
    0 讨论(0)
提交回复
热议问题