读书人

try catch话语出错了

发布时间: 2011-12-20 22:26:41 作者: rapoo

try catch语句出错了

Java code
public class ProductManager {    public void save(File f) {        try {            ObjectOutputStream oos = new ObjectOutputStream(                    new FileOutputStream(f));            Scanner input = new Scanner(System.in);            System.out.println("Please input prodcutID");            String id = input.next();            System.out.println("Please input prodcut name:");            String name = input.nextLine();            System.out.println("Please input the price:");            double price = input.nextDouble();            System.out.println("Please input the nunmer:");            int count = input.nextInt();            Product p = new Product(id, name, count, price);            oos.writeObject(p);                    } catch (FileNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();//下面这句代码中,提示无法解析oos,oos不是就在try里面定义的吗?为什么?        } finally{            oos.close();        }    }}


[解决办法]
public void save(File f) {
ObjectOutputStream oos =null;
try {
oos = new ObjectOutputStream(
new FileOutputStream(f));
Scanner input = new Scanner(System.in);

System.out.println("Please input prodcutID");
String id = input.next();
System.out.println("Please input prodcut name:");
String name = input.nextLine();
System.out.println("Please input the price:");
double price = input.nextDouble();
System.out.println("Please input the nunmer:");
int count = input.nextInt();
Product p = new Product(id, name, count, price);
oos.writeObject(p);


} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

//下面这句代码中,提示无法解析oos,oos不是就在try里面定义的吗?为什么?
} finally{
oos.close();
}

try里面的局部变量,finally怎么能看到呢?
大括号的范围啊

读书人网 >J2SE开发

热点推荐