我希望以下代码能够在设置静态变量值的语句之前打印行,但是它没有按预期工作。
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();
}
}
}
输出抛出异常“银行处于危机中”,但它应首先打印一些“收取现金...”消息然后抛出异常消息......
答案 0 :(得分:5)
问题是你的PrintWriter
永远不会被刷新。它正在累积数据,但它永远不会将其写入控制台,因为在缓冲区已满之前会抛出异常。
如果您在引发异常的来电之前致电writer.flush()
,则会看到预期的消息。
如果您在finally块中关闭作者,则会在数据关闭时看到数据,因为这也会使作者刷新...但在异常之后,如catch
在finally
之前执行。
如果您使用try-with-resources
块,则会在异常之前看到数据,因为close
发生在"嵌套& #34;尝试/终于,有效:
try (PrintWriter writer = new PrintWriter(System.out)) {
Bank hsbc = new Bank();
...
} catch(Exception e){
// writer will already be closed here
e.printStackTrace();
}
答案 1 :(得分:0)
你忘记了
writer.flush();
printf
方法不会自动刷新,您的消息位于永远不会发送到控制台的缓冲区中。
答案 2 :(得分: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)