简体   繁体   中英

Integer.parseInt removes leading 0

My program is asking for the time and I am splitting the time by the ":" . For some reason if I input something with a 0 before as the first value, it removes it. Any idea why it does this?

This is my code:

import java.util.Scanner;

public class ArrivalTime {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        boolean rushHour;

        System.out.print("Enter The Time Fiona Will Leave For Work (HH:MM): ");
        String departureTime = sc.nextLine();

        String parts[] = departureTime.split(":");

        int departureHour = Integer.parseInt(parts[0]);
        int departureMinute = Integer.parseInt(parts[1]);

        System.out.println(departureHour + " " + departureMinute);
    }
}
int departureHour = Integer.parseInt(parts[0]);
int departureMinute = Integer.parseInt(parts[1]);
System.out.println(departureHour + " " + departureMinute);

Integer.parseInt(ANY_INTEGER_VALUE) returns integer. eg Integer.parseInt(03) will return 3 instead of 03.

If you want to display the given input

03:09

as it is, you should keep the String displayed as it is:

System.out.println (parts[0] + " " + parts[1]);

Parse to int for calculation purposes only.

Note: I have edited the below part after reading @Elliot's comment.

Or as @Elliot specified in his comment:

System.out.printf("%02d %02d%n", departureHour, departureMinute);

The problem is the Integer.parseInt() call. When you pass there some String with leading zeros they will be removed and the result is a natural number. If you want to see the leading zeros just write:

String departureHour = parts[0];
String departureMinute = parts[1];

System.out.println(departureHour + " " + departureMinute);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM