我正在编写一个约会程序,允许用户输入约会日期、描述和约会类型。一切正常,直到他们选择“打印范围”,打印一系列日期,当他们选择这样做时,它会告诉他们输入开始日期和结束日期,然后程序会从这些日期之间提取所有约会并将它们显示到输出框中。
以下是我在打印范围方面遇到的错误:
AppointmentNew.java:68: unreported exception java.text.ParseException; must be caught or declared to be thrown
Date lowDate = sdf.parse(stdin.nextLine());
^
AppointmentNew.java:70: unreported exception java.text.ParseException; must be caught or declared to be thrown
Date highDate = sdf.parse(stdin.nextLine());
^
AppointmentNew.java:77: unreported exception java.text.ParseException; must be caught or declared to be thrown
Date newCurrentDate = sdf.parse(currentDate);
我想我可能应该做一个 try/catch 块,但我不太确定如何做到这一点,并且想知道是否有人可以为我提供答案或示例来修复这些错误。
这是我认为发生解析错误的一些代码:
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AppointmentNew
{
public static void main (String[] args) throws Exception
{
if (choiceNum == 2)
{
System.out.print("\n\n\tEnter START Date in mm/dd/yyyy format: ");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date lowDate = sdf.parse(stdin.nextLine());
System.out.print("\n\n\tEnter END Date in mm/dd/yyyy format: ");
Date highDate = sdf.parse(stdin.nextLine());
for(int i = 0; i < list.size(); i++)
{
int dateSpot = list.get(i).indexOf(" ");
String currentDate = list.get(i);
currentDate.substring(0, dateSpot);
Date newCurrentDate = sdf.parse(currentDate);
if (newCurrentDate.compareTo(lowDate) >= 0 && newCurrentDate.compareTo(highDate) <= 0)
{
System.out.println("\n\t" + list.get(i));
}
}
}
为什么你会收到错误:
如何修复它:
将有问题的代码括起来try catch
- 这就像说,我将捕获错误,记录它并希望能够对此采取一些措施。
try { // add this line
System.out.print("\n\n\tEnter START Date in mm/dd/yyyy format: ");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date lowDate = sdf.parse(stdin.nextLine());
System.out.print("\n\n\tEnter END Date in mm/dd/yyyy format: ");
Date highDate = sdf.parse(stdin.nextLine());
for(int i = 0; i < list.size(); i++)
{
int dateSpot = list.get(i).indexOf(" ");
String currentDate = list.get(i);
currentDate.substring(0, dateSpot);
Date newCurrentDate = sdf.parse(currentDate);
if (newCurrentDate.compareTo(lowDate) >= 0 && newCurrentDate.compareTo(highDate) <= 0)
{
System.out.println("\n\t" + list.get(i));
}
}
} catch (ParseException ex) {
ex.printStackTrace(); // or log it using a logging framework
}
或者把它扔到 main 上 - 在这里,这就像在说:无论是谁调用这个方法,如果发生这个问题请注意:
public static void main (String[] args) throws Exception
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)