我正在学习 android,并且是 Java 新手,但对编程并不陌生(使用 Eclipse)。我正在尝试在方法中执行这样的示例代码:
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());
}
...
}
假设定义了所有其他语法和变量。我收到以下错误:
InputStream` cannot be resolved to a variable.
即使在导入java.io.InputStream;
之后这仍然很奇怪
如果我在方法外部声明 InputStream
,则会出现错误,即
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
的本地声明无法解析,但全局声明却解析了。
最佳答案
您的 if
语句后面跟着一个语句。变量的声明需要一个 block 。如果允许您在那里声明一个变量,它将没有可见的作用域并且没有任何作用。
这应该有效:
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. */
...
}
关于java - 声明输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9346939/