2011-09-09 32 views
0

こんにちは、私は文字列からいくつかの整数を取得するために使用する次のコードを得ました。 「 - 」のインデックスのcharがある場合、私は次の番号で文字列を組み合わせることにより、成功裏に負と正の整数を分離していると私は文字列の整数を解析するJava

//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"の数字を除いて私の配列にポジティブなものがあります...アイデアは?

+2

あなただけのビットに値を分割するために、 'degree.split(」「)を'使用していない任意の理由は? –

答えて

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]); 
} 
+0

これはそれですthnx :) – user878813

+0

@ user878813答えを受け入れるよりも –