[英]How do I branch into a specified part of a loop?
int a = 0;
int b = 0;
int c = 0;
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
b = sc.nextInt();
a =+ b;
c =+ (a + 1);
if (c < 20) {
i = 2;
}
}
if I have lines numbered from 0 to 6 inside the loop, the loop would be so if c is less than 20, it repeats the operation "c=+(a+1);" 如果我在循环内有从0到6的行号,则循环将是这样,如果c小于20,它将重复操作“ c = +(a + 1);” until it breaks out of the loop by c>=20. 直到通过c> = 20跳出循环。
this is a simplified code from my program, mine is GUI. 这是我程序的简化代码,我的是GUI。 every time I run the code, it freezes. 每次我运行代码时,它都会冻结。
You can tag a loop and do break
or continue
instructions, but you need design the flow, it is not possible to go into specified line, because java don't use goto
instruction. 您可以标记一个循环并执行break
或continue
指令,但是您需要设计流程,因为Java不使用goto
指令,所以无法进入指定的行。 You can only switch the flow inside loops by those instructions. 您只能按照这些说明在循环内切换流。
myloopTag:
for (...; ...; ...) {
// and you can break current loop by:
break;
// or specific (outer) loop by
break myloopTag;
// you can also use 'continue' to go to the start of the loop and increment again
continue;
// or to 'continue' at a label:
continue myloopTag;
}
use c+=
instead of c=+
. 使用c+=
代替c=+
。 try that, cheers! 试试吧,加油! and b+=
instead of b=+
. 和b+=
代替b=+
。
You're probably very new to the language. 您可能是该语言的新手。 Welcome! 欢迎!
If I understand your description of your intent properly, you want your code to exit the loop when c>=20. 如果我正确理解了您对意图的描述,那么您希望您的代码在c> = 20时退出循环。 Based on your description of numbering your lines and the fact that you have the statement: 根据您对行编号的描述以及以下事实:
if(c<20){
i=2;
}
it seems that you think that the iterator i in the for loop is related to the line that will be executed*. 似乎您认为for循环中的迭代器i与将要执行的行有关*。 This is not the case. 不是这种情况。 The iterator i is a variable that simply holds an integer (just like a
, b
, and c
in your code). 迭代器i是仅包含整数的变量(就像代码中的a
, b
和c
)。
I suggest you take a look at a tutorial on for loops . 我建议您看一下有关for循环的教程 。 It might be helpful for you to review other language basics as well, like how control flow works (this may be a better one to start with, actually). 复习其他语言基础(例如控制流的工作方式)也可能对您有所帮助(实际上,这可能是一个更好的起点)。
*This guess at your intent is further supported by you counting that there are 6 lines and that your loop goes up to 6. *通过计数有6行并且循环上升到6,进一步支持了您的意图猜测。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.