代码之家  ›  专栏  ›  技术社区  ›  hhh

Java:如何在for循环中使用try-catch作为条件?

  •  0
  • hhh  · 技术社区  · 16 年前

    我知道如何通过比较大小和上限来解决问题,但我需要一个查找异常的条件。如果条件中发生异常,我想退出。

    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.
    
            }
    }
    

    一些错误

    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;}&&
                                       ^
    
    2 回复  |  直到 16 年前
        1
  •  6
  •   polygenelubricants    16 年前

    你不应该使用 Exception 对于正常的控制流,不能使用 陈述 作为循环终止条件,需要 boolean 表达 .

    在这种特殊情况下,您可以使用 !numbs.isEmpty() && (j=numbs.pop()) < 999 && false ,它不会评估右手(这将抛出一个 例外情况 假 尽管如此。

    && 在这样的结构中也利用了短路:

    if (s != null && s.startsWith("prefix")) { ...
    
        2
  •  -1
  •   Dane Yezek    14 年前

    例子:

    for (int i = 0; i < 1000; i++) {
    try {
    // do risky stuff that might not work
        }
    catch (Exception e) {
    break;
        } // end catch
    } // end for loop.
    

    发生了什么: 要么你的时间用完了(inti大于1000,循环自然中断),要么你尝试的这次不起作用,所以捕获被命中并调用“中断”(将你踢出for循环)。

    另一种方法是使用while循环,例如:

    int number = 10;
    boolean badStuff = false;
    while (!badStuff) {
    // do stuff you want
       number = number--; // reassign the number to 9, then 8, then 7, and so on.
       if (number = 1) {
         badStuff = true; // or you could skip having a boolean at all and just call break
           }
        } // end while loop
    

    只要你愿意!坏东西被评估为真(即,你宣布坏东西为假,所以!坏东西是真的),循环将继续。在循环中,您可以在if语句中设置“badStuff=true”,以控制何时退出。每次循环运行它都会检查!然后循环中的if语句。这里badStuff是一个布尔值(即总是true或false),在本例中称为“flag”(挥动它以触发更改)。