我期望下面的代码在设置静态变量值的语句之前打印行,但它没有按预期工作。
import java.io.PrintWriter;
class Bank{
private static boolean isInCrisis = false;
public static boolean getIsInCrisis(){return Bank.isInCrisis;}
public static boolean setIsInCrisis(boolean crisis){
return Bank.isInCrisis = crisis;
}
public String getCash() throws Exception{
if(!Bank.isInCrisis){
return new String("$100");
}
else{
throw new Exception("Bank is in crisis");
}
}
}
public class InstanceObjects{
public static void main(String... st) {
try{
Bank hsbc = new Bank();
PrintWriter writer = new PrintWriter(System.out);
writer.printf("collect cash: %s\n",hsbc.getCash());
writer.printf("collect cash: %s\n",hsbc.getCash());
writer.printf("collect cash: %s\n",hsbc.getCash());
writer.printf("collect cash: %s\n",hsbc.getCash());
writer.printf("collect cash: %s\n",hsbc.getCash());
writer.printf("collect cash: %s\n",hsbc.getCash());
writer.printf("collect cash: %s\n",hsbc.getCash());
hsbc.setIsInCrisis(true);
writer.printf("collect cash: %s\n",hsbc.getCash());
writer.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
输出抛出异常“银行处于危机中”,但它应该首先打印一些“收集现金......”消息,然后抛出异常消息......