views:

79

answers:

1

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;}&&
                                   ^
+6  A: 

You shouldn't use Exception for normal control flow, and you can't use a statement as a loop terminating condition, which needs to be a boolean expression.

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 is false, it will not evaluate the right hand (which would throw an Exception), since there's no need to: the overall expression is false nonetheless.

This && short-circuit is also taken advantage of in constructs like this:

if (s != null && s.startsWith("prefix")) { ...
polygenelubricants