在 java 的 do while 循环中只执行一次指令 [英] execute an instruction only one time in a do while loop in java

查看:37
本文介绍了在 java 的 do while 循环中只执行一次指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中,我们如何在do while循环中只执行一次指令

in java, how can we execute an instruction only one time in a do while loop

do{
    int param;

    //execute this onty one time (depends of param)
    //other instructions instructions

}while(condition)

谢谢

推荐答案

将要执行的语句只放入一次是一种方法,当然,这假定语句出现在语句的末尾或开头循环,并且不依赖于循环中发生的事情的条件(之前或之后).如果你有这样的事情:

Putting the statement you want to execute only once is one way of doing it, but, of course, that assumes that the statement comes at the end or beginning of the loop, and doesn't depend on the conditions of what goes on in the loop (either before or after). If you have something like this:

do {
  // do some stuff
  // one time condition
  // do some more stuff
} while(condition);

您将无法轻松地将这些信息拉到循环之外.如果这是您的问题,我的建议是在一次性语句周围放置某种条件,并在语句运行时更新条件.像这样:

you won't easily be able to pull that information outside of the loop. If this is your problem, my suggestion would be to place some sort of condition around the one-time statement(s) and update the condition when the statement has run. Something like this:

boolean hasRun = false;
do {
  // do some stuff
  if(!hasRun) {
    // one time condition
    hasRun = true;
  }
  // do some more stuff
} while(condition);

这篇关于在 java 的 do while 循环中只执行一次指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆