- 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怎么能看到呢?
大括号的范围啊