繁体   English   中英

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

[英]Java: how to have try-catch as conditional in for-loop?

我知道如何通过将大小与上限进行比较来解决问题,但是我想要一个条件来寻找异常。 如果条件发生异常,我想退出。

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;}&&
                                   ^

您不应该将Exception用于正常的控制流,也不能将语句用作循环终止条件,该条件必须是boolean 表达式

在这种情况下,看起来您可以使用!numbs.isEmpty() && (j=numbs.pop()) < 999 之所以有效是因为&&短路,并且如果左手为false ,则它不会求助于右手(这将抛出Exception ),因为不需要这样做:整体表达式为false

这种&&短路也可以在以下结构中利用:

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

另一种方法是简单地将try-catch放入for循环中,并使for运行一定次数。

例:

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

发生的情况:要么时间用完了(int我变得大于1000,并且循环自然中断了),要么这次您尝试执行的操作不起作用,因此捕获成功并调用了“ break”(使您退出了环)。

另一种方法是使用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

只要!badStuff被评估为true(即,您将坏东西声明为false,那么!badStuff将为true),循环将继续。 在循环内部,您可以在if语句中设置“ badStuff = true”,以控制何时退出。 每次循环运行时,它都会检查!badStuff,然后检查循环中的if语句。 这里的badStuff是一个布尔值(即始终为true或false),在这种情况下称为“标志”(挥动它以触发更改)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM