2012-02-19 8 views
2

私はAndroidに慣れていて、Javaには新しくなっていますが、プログラミングには新しくない(Eclipseを使用しています)。私は方法の中でこのようなサンプルコードを実行しようとしています:InputStreamを宣言する

private void dummy() { 
    try { 
     URL url = new URL(quakeFeed); 
     URLConnection connection; 
     connection = url.openConnection(); 
     HttpURLConnection httpconnection = (HttpURLConnection)connection; 
     int responseCode = httpconnection.getResponseCode(); 
     if(responseCode == HttpURLConnection.HTTP_OK) 
      InputStream inp = new BufferedInputStream(httpconnection.getInputStream()); 
    } 
... 
} 

他のすべての構文と変数が定義されているものとします。理由もjava.io.InputStream;

私は法の外InputStreamを宣言した場合、エラーが消灯をインポートした後に奇妙である

InputStream` cannot be resolved to a variable.

、すなわち

InputStream inp; 
private void dummy() { 
    try { 
     URL url = new URL(quakeFeed); 
     URLConnection connection; 
     connection = url.openConnection(); 
     HttpURLConnection httpconnection = (HttpURLConnection)connection; 
     int responseCode = httpconnection.getResponseCode(); 
     if(responseCode == HttpURLConnection.HTTP_OK) 
     // Changed 
      inp = new BufferedInputStream(httpconnection.getInputStream()); 
    } 
    ... 
} 

私は好奇心:私は次のエラーを取得しますローカル宣言InputStreamを解決できませんでしたが、グローバル宣言は解決されました。

答えて

5

ifステートメントの後にはステートメントが続きます。変数の宣言にはブロックが必要です。そこに変数を宣言することが許されていれば、それは目に見える範囲を持たず目的を果たせません。

これは動作するはずです:

if(responseCode == HttpURLConnection.HTTP_OK) 
{ /* Note the brace to start a block! */ 
    InputStream inp = new BufferedInputStream(httpconnection.getInputStream()); 
    /* Now use the stream within the block. */ 
    ... 
} 
+0

[OK]をおかげで私はこのことを認識波平。 –