2013-02-12 92 views
0

我有兩個連續的for循環,我需要將其中一個變量的值傳遞給另一個for循環內的實例。如何在連續for循環之間傳遞變量值?

for(int x=0; x< sentence.length(); x++) { 

    int i; 
    if (!Character.isWhitespace(sentence.charAt(x))) 
     i = x ; 
     break;  
} 

for (int i ; i < sentence.length(); i++) { 
    if (Character.isWhitespace(sentence.charAt(i))) 
    if (!Character.isWhitespace(sentence.charAt(i + 1))) 
} 

這僅僅是一個我的節目的一部分,並且我的目的是指派x的值(從第一個for循環)至i變量(從第二個for循環),以使我不會從0而是從開始x的值(打破了之前的第一個for循環)...

+0

我是本地第一個循環,有沒有辦法讓內第二個for循環在本地訪問。爲什麼不嘗試使用全局變量(在for循環之外),並且在跳出第一個for循環之前更新變量的值。然後您可以在第二個循環中訪問相同的值。 – code82 2013-02-12 14:12:01

+0

爲什麼不使用'array'而不是'int',其中可以添加第一個循環中的所有值並在第二個循環中使用該數組變量! – dShringi 2013-02-12 14:16:46

回答

0
int x; 
for(x = 0; x < sentence.length; x++) 
    if(!Character.isWhitespace(sentence.charAt(x))) 
     break; 

for(int i = x; i < //And so on and so fourth 
+0

非常感謝你:)它現在的作品! – user2052015 2013-02-12 14:38:43

1

它看起來像Java,是嗎?

您必須在循環塊中聲明「i」變量。順便說一句,如果「i」不是一個循環計數器給這個變量一個有意義的名稱(並且x與循環計數器不相關),作爲一種良好的做法。

此外,你可能有一個錯誤,因爲休息是不符合條件表達式塊(第一個循環)。

int currentCharPosition = 0; //give a maningful name to your variable (keep i for loop counter) 

for(int i=0; i< sentence.length(); i++) { 

      if (!Character.isWhitespace(sentence.charAt(x))){ 
       currentCharPosition = x ; 
       break; //put the break in the if block 
      } 

} 

while(currentCharPosition < sentence.length()) { 
      ... 
      currentCharPosition++; 
} 
0
int sentenceLength = sentence.length(); 
int[] firstLoopData = new int[sentenceLength -1]; 
for(int x=0, index=0; x < sentenceLength; x++) { 
    if (!Character.isWhitespace(sentence.charAt(x))){ 
     firstLoopData[index] = x; 
     index++; 
     break; 
    } 
} 

for(int tempInt: firstLoopData){ 
    //your code... 
}