Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While else statement equivalent for Java?

What is the Java equivalent of the while/else in Python? Because it doesn't work in Java. The first chunk was my python code and the second portion is my attempt to translate it into Java. Edit: tring to replicate 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 Attempt

  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);
like image 828
MissSprezzatura Avatar asked Apr 07 '17 16:04

MissSprezzatura


3 Answers

The closest Java equivalent is to explicitly keep track of whether you exited the loop with a break... but you don't actually have a break in your code, so using a while-else was pointless in the first place.

For Java folks (and Python folks) who don't know what Python's while-else does, an else clause on a while loop executes if the loop ends without a break. Another way to think about it is that it executes if the while condition is false, just like with an if statement.

A while-else that actually had a break:

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

could be translated to

boolean noBreak = true;
while (whatever()) {
    if (whateverElse()) {
        noBreak = false;
        break;
    }
    doStuff();
}
if (noBreak) {
    finishUp();
}
like image 161
user2357112 supports Monica Avatar answered Sep 19 '22 01:09

user2357112 supports Monica


Just use one more if statement:

if (temp.nextToABeeper())
    // pick beer
} else {
    while (temp.frontIsClear()) { /* your code */ }
}

Or:

if (temp.frontIsClear())
    while (temp.frontIsClear()) { /* your code */ }
} else if (temp.nextToABeeper()) {
    // pick beer
}
like image 42
ghostprgmr Avatar answered Sep 19 '22 01:09

ghostprgmr


If you look at the Java Backus–Naur form Grammar (Syntax Specification), else never follows a while.

Your solution needs to be modified accordingly. You can put the while in an else, that way you handle the if statement.

if temp.nextToBeeper() {
     //handle
 } else {
      while(temp.frontIsClear()) {
         //handle
      }
 }
like image 25
Jud Avatar answered Sep 22 '22 01:09

Jud