2013-09-16 48 views
0

試圖製作一個漂亮的小程序,但我認爲它試圖用GET請求運行代碼,而不等待用戶輸入。 這不是太多的代碼,所以如果你能幫我指導我一個資源,我可以找到信息來解決這個問題,它會很棒。Java中的動作監聽器等待

@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()); 
     } 
    } 

} 
+0

場外資源請求是題外話。上述代碼中的問題在哪裏。 –

+0

我試過了你的代碼,它沒有任何改動(除了添加導入)沒有任何變化..我使用開放的jdk 1.7 .. –

+0

從API - >「返回與當前Java虛擬機關聯的唯一控制檯對象,如果有的話。這可能意味着一旦你有多個程序和它們的控制檯運行,例如eclipse,這個方法肯定會返回null而不是任何附加的控制檯。 – JBA

回答

1

您的代碼提供了在該線路上NullPointerException

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

這意味着,控制檯對象不會被初始化。

嘗試讀取輸入這樣的:

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

Man theres總是有人比我快:P +1 :) – JBA

+0

非常感謝! .nextline()片段的功能是什麼? –

+0

@ user2783985它從用戶輸入中讀取下一個可用行:) – BackSlash