2013-02-12 96 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... 
}