gpt4 book ai didi

java - 创建两个 BufferedReader 会关闭输入流吗?

转载 作者:行者123 更新时间:2023-12-02 01:01:53 26 4
gpt4 key购买 nike

所以我写了这两个方法:

    public Player readPlayerData() {
Player player = new Player();
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){
System.out.println("What is your name?");
player.setName(br.readLine());
System.out.println("How much money do you have?");
player.setBalance(BigDecimal.valueOf(Double.parseDouble(br.readLine())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(player);
return player;
}

public Currency readPlayerCurrency() {
Currency currency = null;
try(BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in))){
System.out.println("What is your currency?");
currency = Currency.valueOf(br2.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(currency);
return currency;
}

当我一次调用一个时,它们会按预期工作,但是当我依次调用它们时,我会得到一个 java.io.IOException:流已关闭。尝试使用资源是否会以某种方式关闭 System.in 输入流,或者我是否误解了它的工作原理?

最佳答案

Does try with resources close the System.in input stream

是的,确实如此。您不应关闭 System.in 输入流。

参见:

关于java - 创建两个 BufferedReader 会关闭输入流吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60551161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com