I know how to solve the problem by comparing size to an upper bound but I want a conditional that look for an exception. If an exception occur in conditinal, I want to exit.
import java.io.*;
import java.util.*;
public class conditionalTest{
public static void main(String[] args){
Stack<Integer> numbs=new Stack<Integer>();
numbs.push(1);
numbs.push(2);
for(int count=0,j=0;try{((j=numbs.pop())<999)}catch(Exception e){break;}&&
!numbs.isEmpty(); ){
System.out.println(j);
}
// I waited for 1 to be printed, not 2.
}
}
Some Errors
javac conditionalTest.java
conditionalTest.java:10: illegal start of expression
for(int count=0,j=0;try{((j=numbs.pop())<999)}catch(Exception e){break;}&&
^
conditionalTest.java:10: illegal start of expression
for(int count=0,j=0;try{((j=numbs.pop())<999)}catch(Exception e){break;}&&
^
You shouldn’t use
Exceptionfor normal control flow, and you can’t use a statement as a loop terminating condition, which needs to be abooleanexpression.In this particular case, it looks like you can use
!numbs.isEmpty() && (j=numbs.pop()) < 999. This works because&&is short-circuit, and if the left hand isfalse, it will not evaluate the right hand (which would throw anException), since there’s no need to: the overall expression isfalsenonetheless.This
&&short-circuit is also taken advantage of in constructs like this: