Home > OS >  Java int formating?
Java int formating?

Time:12-02

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??

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

CodePudding user response:

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);

CodePudding user response:

tl;dr Use LocalTime.of(hours, minutes), it's most straight-forward

Alternative: Parse with a suitable DateTimeFormatter:

public static void main(String[] args) {
    // single-digit example values
    int hours = 9;
    int minutes = 1;
    // define a formatter that parses single-digit hours and minutes
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:m");
    // use it as second argument in LocalTime.parse
    LocalTime result = LocalTime.parse(hours   ":"   minutes, dtf);
    // see the result
    System.out.println(result);
}

Output:

09:01

CodePudding user response:

Fix

  • use the proper DateTimeFormatter

    LocalTime.parse(hours   ":"   minutes, DateTimeFormatter.ofPattern("H:m"));
    
  • Build the expected default format

    LocalTime.parse(String.format("d:d", hours, minutes));
    

Improve

Use a more appropriate method

LocalTime.of(hours, minutes);
  • Related