简体   繁体   English

Java中的动作侦听器等待

[英]Action listener in Java wait

Trying to make a nifty little program, but I think it's trying to run the code with the GET request, without waiting for the user input. 试图制作一个漂亮的小程序,但我认为它试图通过GET请求运行代码,而不等待用户输入。 It's not that much code, so if you could help me by directing me to a resource where I could find info to fix that issue it'd be awesome. 它的代码不是很多,因此,如果您可以通过将我定向到可以找到解决该问题的信息的资源来帮助我,那就太好了。

@SuppressWarnings("unused")
public class Test {

    public static void main(String args[]) throws IOException {
        BufferedReader rd;
        OutputStreamWriter wr;
        String movie = null;
        Console console = System.console();
        movie = console.readLine("Enter input:");
        try {
            URL url = new URL("http://www.imdbapi.com/?i=&t=" + movie);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.flush();

            // Get the response
            rd = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            line = rd.readLine();
            if (line != null) {
                System.out.println(line);
            } else {
                System.out.println("Sorry! That's not a valid URL.");
            }
        } catch (UnknownHostException codeyellow) {
             System.err.println("Caught UnknownHostException: " + codeyellow.getMessage());
        }
    }

}

Your code gives a NullPointerException on that line: 您的代码在该行上给出了NullPointerException

movie = console.readLine("Enter input:");

That means that the console object doesn't get initialized. 这意味着不会初始化控制台对象。

Try reading input like this: 尝试像这样读取输入:

Scanner s = new Scanner(System.in);
System.out.println("Enter input:");
movie = s.nextLine();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM