2014-11-06 2 views
-2

Я пытаюсь разобрать пользовательский ввод в 24-часовом формате «12:00», но когда я ввожу время, когда минуты меньше, чем тогда, я теряю начало 0. Например. ввод "3:05" возвращает "3: 5 AM"Как сделать parseInt с ведущими 0?

public class TimeFormatException extends Exception { 

    public TimeFormatException()     // time format exception default error message 
    { 
     super("This is an incorrect time"); 
    } 

    public TimeFormatException(String error)  // time format exception with parameters 
    { 
     super(error); 
    } 

} 

public class Clock24 extends TimeFormatException { 

    private int hours;      // instance variables 
    private int min; 
    private boolean isAM; 

    public Clock24()       // default clock24 
    { 
     this.hours = 0; 
     this.min = 0; 
     this.isAM = true; 
    } 

    public Clock24(int hours, int min)  // clock 24 with parameters 
    { 
     this.hours = hours; 
     this.min = min; 
    } 

    public int getHours()     // accessor and mutator for hours 
    { 
     return hours; 
    } 

    public void setHours(int hours) 
    { 
     this.hours = hours; 
    } 

    public int getMin()       // accessor and mutator for minutes 
    { 
     return min; 
    } 

    public void setMin(int min) 
    { 
     this.min = min; 
    } 

    public void setAM(boolean isAm)       // mutator for boolean isAM check 
    { 
     this.isAM = isAM; 
    } 

    public void setTime(int hours, int min)throws TimeFormatException //declare TimeFormatException 
    { 
     if(hours>24 || hours < 0) 
     { 
      System.out.println("Exception!: Hour is incorrect!"); 
     } 
     else if(min>60 || min < 0) 
     { 
      System.out.println("Exception!: Minutes is incorrect!"); 
     } 
     else 
     { 
      if(hours>=12) 
      { 
       hours-=12; 
       this.isAM=false; 
      } 
      else this.isAM = true; 

      this.hours = hours; 
      this.min = min; 
     } 
    } 

    public void setTime(String time) throws TimeFormatException    //declare TimeFormatException 
    { 
     String[] substring = time.split(":"); // split the time into two substrings which will be parsed into integers 
     int hour = -1;       // set hour and minute to a value clearly less than accepted values 
     int minute = -1; 

     try            // try parsing substrings into integers 
     { 
      hour = Integer.parseInt(substring[0]);      
      minute = Integer.parseInt(substring[1]); 

     } 
     catch(NumberFormatException e)     //if this isn't possible because of the format print an error 
     { 
      System.out.println("Exception!: Incorrect format!"); 
     } 
     catch(ArrayIndexOutOfBoundsException e)   //error will also be printed if not enough numbers are typed 
     { 
      System.out.println("Exception!: Incorrect format!"); 
     } 

     this.setTime(hour,minute);      //use hour and minutes as parameter to set the time 
    } 

    public void printTime()        // print the time 
    { 
     String dt = ""; 
     if(this.isAM) 
     { 
      dt = "AM"; 
     } 
     else 
     { 
      dt = "PM"; 
     } 
     System.out.println(this.hours+":"+this.min+" "+dt); 
    } 
} 

import java.util.*; 
public class Clock24Driver { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     Clock24 clock = new Clock24(); 
     Scanner keyboard = new Scanner(System.in); 

     boolean quit = false; 
     while(quit == false) 
     { 
      //Prompt the user 
      System.out.println("Enter a time in the 24-hour notation or enter \"Exit\" to quit"); 
      //Gets the user input 
      String input = keyboard.nextLine(); 
      if(input.equalsIgnoreCase("exit")) 
      { 
       System.out.println("Goodbye!"); 
       break; 
      } 
      try 
      { 
       clock.setTime(input); 
       clock.printTime(); 
      } 
      catch(TimeFormatException e) 
      { 
       System.out.println(e.getMessage()); 
      } 
     } 
    } 


} 
+2

Это не проблема синтаксического анализа. это проблема DISPLAY. вы не ноль - заполняете свой результат. –

+2

'String.format («% 02d », min);' ваш друг. –

ответ

0

Вы анализируемые значения. Java int не сохраняет свой «исходный формат» от синтаксического анализа (это примитивный тип, и тип-оболочка тоже этого не делает). Я предлагаю вам переименовать printTime() в toString(), и я предлагаю вам использовать String.format(String, Object...) и ternary ?: как

@Override 
public String toString() { 
    return String.format("%02d:%02d %s", this.hours, this.min, 
      (this.isAM) ? "AM" : "PM"); 
} 

Затем измените

clock.printTime(); 

к

System.out.println(clock); 
0

изменить способ печати время

public void printTime() // print the time 
{ 
    String dt = ""; 
    if(this.isAM) 
    { 
     dt = "AM"; 
    } 
    else 
    { 
     dt = "PM"; 
    } 
    System.out.println(String.format("%02d:%02d %s", this.hours, this.min, dt); 
} 
Смежные вопросы