在Java中,我们如何能在做执行的指令只有一次,而循环执行一条指令只有一次在一个do while循环在Java
do{
int param;
//execute this onty one time (depends of param)
//other instructions instructions
}while(condition)
谢谢
在Java中,我们如何能在做执行的指令只有一次,而循环执行一条指令只有一次在一个do while循环在Java
do{
int param;
//execute this onty one time (depends of param)
//other instructions instructions
}while(condition)
谢谢
把你想要执行的语句只做一次就是这样做的一种方式,但是,当然,假设语句出现在循环的结尾或开始,并且不取决于什么条件在循环中(在之前或之后)继续。如果你有这样的事情:
do {
// do some stuff
// one time condition
// do some more stuff
} while(condition);
你不会轻易地将该信息拉出循环。如果这是你的问题,我的建议是在一次性声明的周围放置某种条件,并在语句运行时更新条件。事情是这样的:
boolean hasRun = false;
do {
// do some stuff
if(!hasRun) {
// one time condition
hasRun = true;
}
// do some more stuff
} while(condition);
将语句放在任何循环外面会导致每次调用该方法时只执行一次。
将您想要执行的语句只在while循环外移动一次。
假设你想保持循环内的代码(!其他海报建议外移动代码的明显的解决方案),你可以考虑使用一个标志,只有一次执行它:
boolean doneOnce=false;
do{
if (!doneOnce) {
\\execute this only one time
doneOnce=true;
}
\\other instructions instructions
} while (condition)
可能是一个有用的结构例如,如果你一度只有代码之前曾在环其他指令。
我想到这个,但我想知道它是否存在另一种方式来做到这一点 – Eddinho 2010-05-15 15:57:57