gpt4 book ai didi

java - 为什么 readLine() 没有阻塞?

转载 作者:行者123 更新时间:2023-12-02 00:00:31 24 4
gpt4 key购买 nike

给出以下代码,对 readLine() 的第一次调用不会阻塞,同时打印“输入名称:”和“输入地址:”,并且将地址分配给输入的任何内容。为什么?我尝试过将它们放在单独的 try block 中,摆脱循环并通常重新排序。

public class AddressReader {

public static void main(String[] args) {

Path file = Paths.get("d:/java IO/addresses.txt");

try {
Files.createDirectories(file.getParent());
} catch (IOException e) {
System.err.println("Error craeting directory: " + file.getParent());
e.printStackTrace();
System.exit(1);
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int c = 0;
try {
System.out.println("<a>dd an entry or <r>ead entries");
c = br.read();
} catch (IOException e) {
System.out.println("An error has occured, try again");
}
switch (c) {
case 'a':
String name = null;
String address = null;

while (name == null || name == "" || address == null || address == "") {
try {
System.out.println("Enter name:");
name = br.readLine();
System.out.println("Enter address:");
address = br.readLine();
} catch (IOException e) {
System.out.println("An error has occured, try again");
}
System.out.println("name = " + name);
System.out.println("address = " + address);
}
//writeEntry(file, name, address);
break;
case 'r':
//readEntries(file);
break;
default:
System.out.println("Invalid entry, try again.");
}

}

}

最佳答案

这是因为这一行:

c = br.read();

这不会消耗按 ENTER 生成的换行符。

要解决此问题,请改用:

c = br.readLine().charAt(0);

关于java - 为什么 readLine() 没有阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14926678/

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