我有一些java代码有问题。这个程序由大约7个文件组成,但我会尽量保持简短。
我试图用ObjectStream将文件中的一个ObjectStream加载到一个变量中。它给了我一个警告,因为编译器所能看到的就是,我说应该将一个对象抛给ArrayList。当然,编译器不会知道文件中有什么样的对象。作为编码器,我知道文件只能由一个ArrayList而不是其他任何东西组成。于是我搜索了一下网络,发现要压制这个警告,现在它给了我错误:
Schedule.java:34: error: <identifier> expected为了给您提供正在发生的事情的图片,下面是错误发生的代码。此错误不应受任何其他类的影响。
import java.util.*;
import java.io.*;
public class Schedule
{
private static ArrayList<Appointment> schedule;
private static File file;
private static ObjectInputStream objIn;
private static boolean exit;
private static Scanner in = new Scanner(System.in);
public static void main(String[] args)
{
initializeSchedule();
System.out.println("Welcome!");
while(!exit){
System.out.print("write command: ");
Menu.next(in.next());
}
}
public static void initializeSchedule()
{
try{
file = new File("Schedule.ca");
if(!file.exists()){
schedule = new ArrayList<Appointment>();
}
else{
objIn = new ObjectInputStream(new FileInputStream("Schedule.ca"));
@SuppressWarnings("unchecked")
schedule = (ArrayList<Appointment>)objIn.readObject();
objIn.close();
}
} catch (IOException e){
System.out.println("Exception thrown :" + e);
} catch (ClassNotFoundException e){
System.out.println("Exception thrown :" + e);
}
}
public static void exit()
{
exit = true;
}
public static ArrayList<Appointment> getSchedule()
{
return schedule;
}
}错误在initializeSchedule中,就在抑制下,其中调度设置为ObjectStream输入。
发布于 2013-12-08 10:43:09
你不能给作业加注释。移动
@SuppressWarnings("unchecked")方法开始前的行。
发布于 2013-12-08 10:46:55
@SuppressWarnings("unchecked")的正确位置是
类型、字段、方法、参数、构造函数、LOCAL_VARIABLE
因此编译器此时不能解析@抑制警告,而是将其视为语句。如果您将其移动到方法声明或时间表声明之上,则应该可以。
解决这一问题的更好方法是纠正编译器正在抱怨的问题,如下所示:
final Object input = objIn.readObject();
if (input instanceof ArrayList) {
schedule = (ArrayList<Appointment>) input;
} else {
throw new IllegalStateException(); // or whatever suits you
}https://stackoverflow.com/questions/20452405
复制相似问题