Question

Hi i got the following code which i use to get some integers from a string. I am separating successfully the negative and positive integers by combining the string with the next number if the char at the index is "-" and i can put the numbers in an integer array...

   //degree is the String i parse

   String together="";
      int[] info=new int[degree.length()];
      int counter=0;

       for (int i1 = 0; i1 < degree.length(); i1++) {

         if (Character.isSpace(degree.charAt(i1))==false){ 
            if (Character.toString(degree.charAt(i1)).equalsIgnoreCase("-")){
                together="-";
                             i1++;

            }
             together = together + Character.toString(degree.charAt(i1));

            info[counter]=Integer.parseInt(together);
         }
         else if (Character.isSpace(degree.charAt(i1))==true){
             together ="";
            counter++;
         }

But i go this strange problem....the string looks exactly like "4 -4 90 70 40 20 0 -12" and the code parses and puts the integers into the array only to the "0" number i mean i get all the number negatives and positives into my array except the last "-12" number... any ideas?

Was it helpful?

Solution

I think there's a much simpler solution to your problem:

// First split the input String into an array,
// each element containing a String to be parse as an int
String[] intsToParse = degree.split(" ");

int[] info = new int[intsToParse.length];

// Now just parse each part in turn
for (int i = 0; i < info.length; i++)
{
    info[i] = Integer.parseInt(intsToParse[i]);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top