gpt4 book ai didi

java - 代码突出显示为语法错误。为什么?

转载 作者:行者123 更新时间:2023-11-30 05:51:12 25 4
gpt4 key购买 nike

我是 java 的新手,我正在尝试编写这段代码,但不知何故,它在使用我的变量时将其视为错误。已宣布为ofc。

import java.io.*;

public class FileRead {
public void readCountries(String file){
try{
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("countries"));
Object obj = null;
while ((obj = inputStream.readObject()) != null) {
if (obj instanceof Country) {
System.out.println(((Country)obj).toString());
}
}
} catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectInputStream
try {
if (inputStream != null) { //////////ERROR: inputStream cannot be resolved to a variable
inputStream.close(); //////////// Same here
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

最佳答案

将您的 inputStream 声明移到 try block 之外。如果您在 try 内部定义,它在 try block 之外是不可见的。

    ObjectInputStream inputStream = null;
try{
inputStream = new ObjectInputStream(new FileInputStream("countries"));
........
}

关于java - 代码突出显示为语法错误。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13039475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com