0

嗨,我得到了以下代码,我用它来从字符串中获取一些整数。如果索引处的字符是“-”,我通过将字符串与下一个数字组合成功地分离负整数和正整数,并且我可以将数字放入整数数组中......

   //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++;
         }

但是我遇到了这个奇怪的问题....字符串看起来完全像“4 -4 90 70 40 20 0 -12”,代码解析并将整数放入数组中,只有“0”数字我的意思是我得到了所有除了最后一个“-12”数字之外,我的数组中的负数和正数......有什么想法吗?

4

1 回答 1

2

我认为您的问题有一个更简单的解决方案:

// 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]);
}
于 2011-09-09T10:56:07.050 回答