我是Java的新手,可能看不清楚,但这是我的问题:
出于某种原因,我无法访问我班级的方法MenuItem:
public class MenuItem {
String name;
double price;
public MenuItem (String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return this.name;
}
public String toString() {
return this.name + "\t" + this.price;
}
}
Run Code Online (Sandbox Code Playgroud)
在下面的代码片段中,我的IDE强调了方法getName()red并说:
"找不到标志"
这是代码:
public static void main(String[] args) {
ArrayList<Object> menuItems = new ArrayList<Object>();
menuItems.add(new MenuItem("Pizza", 2.22));
System.out.println(menuItems.get(0).getName());
}
Run Code Online (Sandbox Code Playgroud)
我将我的代码与其他代码进行了比较,但没有找到任何区别.
不知怎的,这种toString()方法完美无缺.当我删除方法时,它返回this.name + "\t" + this.price;而不是它返回filechallenge.MenuItem@15db9742的内容.
有人有想法吗?我真的不明白......
我FileInputStream第一次使用a 并尝试Item从文件加载objects().
这是我的代码:
try {
FileInputStream fi = new FileInputStream(f);
ObjectInputStream reader = new ObjectInputStream(fi);
while (true) {
Item i = (Item)reader.readObject();
System.out.println(i.getName());
}
} catch (Exception e) {
System.out.println(e.toString());
}
Run Code Online (Sandbox Code Playgroud)
我已经读过这是执行它的标准方法,代码工作正常.然而,这种方式fi并reader永远不会关闭,因为编译器跳转到catch只要一个块EOFException被抛出.
编译器不会让我关闭fi,并reader在catch或finally块.这真的是它应该如何吗?如何正确关闭输入对象?