java - 而 else 语句等同于 Java?

标签 java python if-statement while-loop

Python 中 while/else 的 Java 等价物是什么?因为它在 Java 中不起作用。第一部分是我的 Python 代码,第二部分是我尝试将其翻译成 Java。 编辑:尝试复制 while-else

  while temp.frontIsClear():
    if temp.nextToABeeper():
       temp.pickBeeper()
       count += 1
    temp.move()
 else:
    if temp.nextToABeeper():
       temp.pickBeeper()
       count += 1
 print "The count is ", count

Java 尝试

  Robot temp = new Robot();
  int count = 0;
  while (temp.frontIsClear())
  {
     if (temp.nextToABeeper())
     {
        temp.pickBeeper();
        count += 1;
     }
     temp.move();
  }
  else
  {
     if (temp.nextToABeeper())
     {
        temp.pickBeeper();
        count += 1;
     }
  }
  print ("The count is ", count);

最佳答案

最接近的 Java 等价物是显式跟踪您是否使用 break 退出循环...但您实际上没有 break 在您的代码中,因此首先使用 while-else 毫无意义。

对于不知道 Python 的 while-else 是做什么的 Java 人(和 Python 人)来说,如果循环结束没有中断。另一种思考方式是,如果 while 条件为假,它就会执行,就像 if 语句一样。

实际上有一个break的while-else:

while whatever():
    if whatever_else():
        break
    do_stuff()
else:
    finish_up()

可以翻译成

boolean noBreak = true;
while (whatever()) {
    if (whateverElse()) {
        noBreak = false;
        break;
    }
    doStuff();
}
if (noBreak) {
    finishUp();
}

关于java - 而 else 语句等同于 Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43283142/

相关文章:

使用 log4j 自定义布局类运行应用程序时,jBoss 上出现 java.lang.LinkageError

java - JFileChooser.getTypeDescription(File f) 的值来自哪里

java - 模拟一个返回 Stream 并被多次调用的方法

python - 在 Python 中对 Corba 进行单元测试

java - 如何向 Android 应用添加新页面?

python - Django : Syncdb incorrectly warns that many-to-many field is stale

python - 在 django 中向管理员显示多个选择

python - 使用 while 或 if 作为递归条件会导致不同的结果

javascript - if 忽略条件 JQuery

java - “if” 语句与 OO 设计 - 2