[英]How to pass variable values between successive for loops?
我有两个连续的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循环)...
看起来像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++;
}
您需要了解Java块范围:
像这样在for循环外声明变量
// Declare what you want to access outside here.
...
for(int x = 0; x< sentence.length(); x++) {
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
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...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.