我对Java非常陌生,也许我的问题有点让人恼火。
我的代码中有两个for循环,我希望通过for-else语句转到每个循环的开头。
public static void main(String[] args)
{
int[][] x=new int[1000][1000];
int[] Z=new int[1000];
lable1:
for(int i=1; i<=1000; i++)
{
Z[i]=rand1.nextInt(1000);
System.out.println("Z["+i +"] = " + Z[i] );
if(Z[i]>0 && Z[i]<=Nk)
{
int Z1=Z[i]-1;
lable2:
for(int j = 1; j<=Z1;j++ )
{
x[i][j]= rand2.nextInt(1000);
sum+=x[i][j];
if( sum<1000)
{
x[i][(j+1)]=1000-sum;
System.out.println("x[" + i+"][" + j + "] = " + x[i][j]);
System.out.println("Nx[" + i+"][" + (j+1) + "] = " +x[i][(j+1)]);
}
else{
// ????
//Goto lable2;
}
}
}
else{
//goto label1;
// ????
}
}
}发布于 2012-10-08 17:04:40
您可以使用以下命令break到任何已定义的标签(在作用域内):
break label;continue也是如此。
Here是值得一读的东西。
在您的特定示例中,删除else将执行您想要的操作。
发布于 2012-10-08 17:06:38
只需使用continue关键字..它将继续进行下一次迭代。无需标记您的循环..因为您没有从内部循环继续外部循环..或者,如果您想使用带有外部循环的continue,您可以使用带有标签的continue ...
您应该使用j = 0 to j < z1中的for循环。
for(int j = 0; j < Z1;j++ ) {
if( sum<1000) {
x[i][(j+1)]=1000-sum;
System.out.println("x[" + i+"][" + j + "] = " + x[i][j]);
System.out.println("Nx[" + i+"][" + (j+1) + "] = " +x[i][(j+1)]);
}
else{ // Not needed if your else does not contain anything else..
continue;
}
}事实上,您根本不需要else 块。如果您没有在其中做任何进一步的处理..
去掉它就行了..它会自动转到你的循环..
Suggestion:-您应该使用编码约定。变量名以lowercase letter或underscore开头。(Z1 -> z1)
发布于 2012-10-08 17:09:20
您的位置如下:
public static void main(String[] args) {
int[][] x = new int[1000][1000];
int[] Z = new int[1000];
boolean resetOuterCycle = true;
for (int i = 0; i < 1000; i++) {
Z[i] = rand1.nextInt(1000);
System.out.println("Z[" + i + "] = " + Z[i]);
if (Z[i] > 0 && Z[i] <= Nk) {
int Z1 = Z[i] - 1;
boolean resetInnerCycle = true;
for (int j = 0; j < Z1; j++) {
x[i][j] = rand2.nextInt(1000);
sum += x[i][j];
if (sum < 1000) {
x[i][(j + 1)] = 1000 - sum;
System.out.println("x[" + i + "][" + j + "] = " + x[i][j]);
System.out.println("Nx[" + i + "][" + (j + 1) + "] = " + x[i][(j + 1)]);
} else if (resetInnerCycle) {
j = 0;
resetInnerCycle = false;
}
}
} else if (resetOuterCycle) {
i = 0;
resetOuterCycle = false;
}
}
}https://stackoverflow.com/questions/12778428
复制相似问题