0

我期望下面的代码在设置静态变量值的语句之前打印行,但它没有按预期工作。

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(); 
    }
}
}

输出抛出异常“银行处于危机中”,但它应该首先打印一些“收集现金......”消息,然后抛出异常消息......

4

3 回答 3

5

问题是你PrintWriter的从来没有被冲洗过。它正在累积数据,但它从不将其写入控制台,因为在其缓冲区已满之前抛出异常。

如果您writer.flush()在引发异常的调用之前调用,您将看到预期的消息。

如果您在 finally 块中关闭写入器,您将在它关闭时看到数据,因为这也会刷新写入器......但是异常之后,就像catch之前执行的那样finally

如果您改用try-with-resources块,您将在异常之前看到数据,因为close在“嵌套”尝试/最终中发生,有效地:

try (PrintWriter writer = new PrintWriter(System.out)) {
    Bank hsbc = new Bank();
    ...
} catch(Exception e){
    // writer will already be closed here
    e.printStackTrace(); 
}
于 2013-09-10T19:59:08.537 回答
0

你忘了

writer.flush();

printf方法不会自动刷新,您的消息位于永远不会发送到控制台的缓冲区中。

于 2013-09-10T19:59:22.320 回答
0

在获取引发异常的消息之前尝试刷新流。

public class Main{ 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());
        writer.flush();
        hsbc.setIsInCrisis(true);
        writer.printf("collect cash: %s\n",hsbc.getCash());            
        writer.close(); 
    }catch(Exception e){
        e.printStackTrace(); 
    } } }

印刷:

collect cash: $100
collect cash: $100
collect cash: $100
collect cash: $100
collect cash: $100
collect cash: $100
collect cash: $100
java.lang.Exception: Bank is in crisis
    at Bank.getCash(Main.java:13)
    at Main.main(Main.java:32)
于 2013-09-10T20:01:12.030 回答