I’m trying to read a date out of a text file then parse the String into a date so I can read it into my array. I keep getting an error when I try Date date = sdf.parse (token.nextToken ());. What can I do to convert the string I read from my text file into a date?
Date set
void setDate(Date d)
{
date =d;
}
File Reader
void read ()
{
SimpleDateFormat sdf = new SimpleDateFormat ("dd/MM/yyyy");
int cnt = 0;
try
{
FileReader fr = new FileReader ("oefeningtaak.txt");
BufferedReader br = new BufferedReader (fr);
boolean canread = true;
while (canread == true)
{
String lyn = br.readLine ();
if (lyn == null)
{
canread = false;
}
else
{
array [cnt] = new Mainobject ();
StringTokenizer token = new StringTokenizer (lyn, "*");
String students = token.nextToken ();
String vak = token.nextToken ();
String maxpunt = token.nextToken ();
String punt = token.nextToken ();
Date date = sdf.parse (token.nextToken ());
array [cnt].setStudents (students);
array [cnt].setVak (vak);
array [cnt].setMaxpunt (Integer.parseInt (maxpunt));
array [cnt].setPunt (Integer.parseInt (punt));
array [cnt].setDate (date);
array [cnt].report ();
cnt++;
}
}
}
catch (IOException err)
{
System.out.println (err.toString ());
}
}
The error I get is
The method “java.util.Date parse(java.lang.String $1) throws java.text.ParseException: “can throw the checked exception “java.text.ParseException”. so its invocation must be enclosed in a try statement that catches the exception, or else this method must be declared to throw the exception
You are catching an IOException, but you are not catching, or declaring, the ParseException.
You need to either catch it or declare that your method may throw it, as it is a checked exception.