0

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

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.");
    }

}

}

4

2 回答 2

3

这是因为这一行:

c = br.read();

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

要解决此问题,请改用:

c = br.readLine().charAt(0);
于 2013-02-17T22:24:36.080 回答
0

除了已经说过的内容之外,对于您要尝试做的事情,我建议您改用控制台:

Console console = System.console();
String name = console.readLine("Create a name.");
char[] password = console.readPassword("Create a password.");
System.out.println(name + ":" + new String(password));
于 2013-02-17T22:18:26.477 回答