我期待以下代碼在設置靜態變量值的語句之前打印行,但它不按預期工作。java字節碼是不是按順序執行?
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();
}
}
}
輸出拋出異常「銀行危機」,但它應該首先打印的「收取現金......」消息的一些線條,然後扔異常信息...
請包括整個堆棧跟蹤,並指示在聲明中'主()'在異常被拋出(應該是第二個'at'線)。 –
@mabbas,以及'hsbc.setIsInCrisis(true)'上面的printf語句呢?輸出應該是:收集現金$ 100,....,例外被捕獲....銀行處於危機...... –
java.lang.Exception:銀行處於危機 \t at Bank.getCash(InstanceObjects.java: 13) \t at InstanceObjects.main(InstanceObjects.java:31) –