如果是a>m,我想连续打印三次1。我尝试过通过for循环运行它。
for(int i = 0; i<message.length; i+=3){
if(a>m){
System.out.println("1");
}
}我希望程序在连续三次命中第一个集合的a>m时立即停止。
发布于 2015-05-27 12:03:45
添加连续命中的计数器,该计数器最初设置为零。每次命中时都会递增该值。一旦计数器数到三,就跳出循环。否则,继续循环:
int consecutiveHits = 0;
for (...) {
if (a > m) {
...
consecutiveHits++;
if (consecutiveHits == 3) {
break;
}
} else {
consecutiveHits = 0;
}
}发布于 2015-05-27 12:02:25
如果您只想将'1‘打印三次,那么您似乎没有正确使用for语法。您可能希望它为i++,而不是增量语句为i+=3。为了进行比较,您需要i<3,而不是i<message.length。所以这可能就是你想要的:
for(int i = 0; i<3; i++){ //go through the loop three times. Print 1 in the loop only if a>m.
if(a>m){
System.out.println("1");
}
}请参阅for loop here上的语法。
它在每次循环中执行第三条语句,所以当i初始化为0,语句i+=3结束时,第一次循环的i将是0,下一次将是3,然后是6,然后是9,依此类推,直到您的条件变为false (正如您已经编写的那样,它将一直运行到i>=message.length,所以如果message.length是3,那么您只需要在编写代码的过程中经历一次循环)。
发布于 2015-05-27 12:03:27
这意味着您希望通过将从循环中分离出来。有两种主要方法可以做到这一点:
使用break关键字:
Java包括keyword for breaking out of loops和keyword for skipping certain parts of loops.,如果你想在某个术语适用时跳出循环--你可以直接使用它-- break; --它会当场停止循环。示例:
for(int i = 0; i<message.length; i+=3){
if(a>m){
System.out.println("1");
break; // you go out of the loop-
}
}
// and the code goes on from here.使用标志:
在术语part中,您可以使用布尔值来跟踪循环的每次执行情况。这样,您就可以跟踪它,并在需要时跳出循环。示例:
Boolean myFlag = true;
for(int i = 0; i<message.length && myFlag ; i+=3){ // notice how the term changed.
if(a>m){
System.out.println("1");
myFlag = false; // The term will no longer fullfill and you will go out of the loop.
}
}https://stackoverflow.com/questions/30472878
复制相似问题