Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java int formating?

I want the user to input hours and minutes for a Local.Time from 00 to 23 and from 00 to 59, I scanned this as an int. It works but for values from 00 to 09 the int ignores the 0 and places then as a 0,1,2…9 instead of 00,01,02,03…09; this breaks the Local.Time since, for example "10:3"; is not a valid format for time.

I have read I can format this as a String, but I don’t think that helps me since I need an int value to build the LocalTime and subsequent opperations with it.

There is a way of formatting this while kepping the variable as an int??
Can I code this differently to bypass this??
Am I wrong about how these classes work??

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am pretty new to these concepts

Here is the code I am using

int hours;
int minutes;

System.out.println("Input a number for the hours (00-23): ");
hours = scan.nextInt();

System.out.println("Input a number for the minutes (00-59): ");
minutes = scan.nextInt();

LocalTime result = LocalTime.parse(hours + ":" + minutes);

I tried using the NumberFormat class but it returns an error when trying to declare its variables (something like it is an abstract variable and cannot be instanced)

I also tried using the String format but I don’t really know what to do with that string after that, it asks me for a int and not a string to build this method

>Solution :

First: an int doesn’t differentiate between 09 and 9. They are the same value: the number nine.

Next: if you already have numbers, then going back to a string to produce a date is an anti-pattern: you are losing type checking by this. So instead of using LocalTime.parse and constructing the input from int values, you should simply use LocalTime.of(hours, minutes):

LocalTime result = LocalTime.of(hours, minutes);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading