Java BufferedReader.readLine() 不等待用户输入

Java BufferedReader.readLine() not waiting for user input

我的 BufferedReader 实例有问题,在继续之前没有等待用户输入。

static BufferedReader in;

public class {
    public static void main(String[] args) {
        try{
            in = new BufferedReader(new InputStreamReader(System.in));
            String input;
            System.out.println("prompt");
            input = in.readLine();
            if(input.equals("Y")){
                //do something
            }else {
                //do something else
            }
        }catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

当我 运行 程序时,会发生什么,它只是跳过 in.readLine() 并在 if 语句中抛出空异常。我对正在发生的事情一头雾水,因为我对另一个仍然有效的项目使用了相同的代码。

谢谢!

是的,你必须处理异常,只需添加:

public static void main(String[] args) throws IOException {
 
        in = new BufferedReader(new InputStreamReader(System.in));
        String input;
        System.out.println("prompt");
        input = in.readLine();
        if(input.equals("Y")){
            System.out.println("it works !!");
        }else {
            System.out.println("it's not a Y :(");
        }
    }

找到答案了。使用 gradle 到 运行 程序和我的任务没有 standardInput = System.in 的参数。仍在习惯项目构建软件!