通过输入一条允许用户重试的消息来使用户输入无效条目时出错

时间:2019-07-26 13:16:40

标签: java exception

该程序假设将用户输入的24小时格式时间转换为12小时(如果输入有效)。它应发送一条消息,指出“输入无效,请重试”,程序应恢复为输入提示。

public class TimeFormatException {


  public static void main(String[] args) {

    Scanner inputTime = new Scanner(System.in); 
    String time ;
    char stopper;

    do {            
      System.out.println("Enter time in 24-hour notation: ");
      time= inputTime.nextLine();       
      SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");      
      DateFormat timeFormatter = new SimpleDateFormat("hh:mm aa");      
      Date nullTime= null;
      String outputTime= null;  
      timeFormatter = new SimpleDateFormat("hh:mm");
      try {
        nullTime= timeFormat.parse(time);     
        outputTime= timeFormatter.format(nullTime);
      } catch (ParseException ex) {   
        ex.printStackTrace();
      }
      System.out.println("That is the same as "+ outputTime);   
      System.out.println("Again (y/n)");    
      Scanner i = new Scanner(System.in);
      stopper = i.next().charAt(0); 
    } while (stopper == 'y' || stopper == 'Y');
  }
}

-

java.text.ParseException: Unparseable date: "2"
That is the same as null
Again (y/n)
    at java.text.DateFormat.parse(Unknown Source)
    at TimeFormatException.main(TimeFormatException.java:39)

1 个答案:

答案 0 :(得分:1)

您只需在continue块内添加一个catch

try {
   nullTime= timeFormat.parse(time);     
   outputTime= timeFormatter.format(nullTime);
} catch (ParseException ex) { 
    ex.printStackTrace();
    continue;
}

这将导致循环从头开始。

您可能要避免打印堆栈跟踪,而是打印一条用户友好的消息

try {
   nullTime= timeFormat.parse(time);     
   outputTime= timeFormatter.format(nullTime);
} catch (ParseException ex) { 
    System.out.println("The time is not in the expected format");
    continue;
}