Dal*_*ito 2 java string integer localtime java-time
我希望用户输入 Local.Time 从 00 到 23 和从 00 到 59 的小时和分钟,我将其扫描为整数。它可以工作,但对于从 00 到 09 的值,int 会忽略 0 并将其放置为 0,1,2...9 而不是 00,01,02,03...09;这会破坏 Local.Time,例如“10:3”;不是有效的时间格式。
我读过我可以将其格式化为字符串,但我认为这对我没有帮助,因为我需要一个 int 值来构建 LocalTime 以及随后的操作。
有一种方法可以在将变量保留为 int 的同时对其进行格式化?我可以用不同的方式编码来绕过这个吗?我对这些课程的运作方式有误吗?
我对这些概念很陌生
这是我正在使用的代码
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);
Run Code Online (Sandbox Code Playgroud)
我尝试使用 NumberFormat 类,但在尝试声明其变量时返回错误(比如它是一个抽象变量,无法实例化)
我也尝试使用字符串格式,但我真的不知道之后如何处理该字符串,它要求我提供一个 int 而不是字符串来构建此方法
首先:anint不区分 09 和 9。它们是相同的值:数字 9。
接下来:如果您已经有数字,那么返回字符串来生成日期是一种反模式:您将因此失去类型检查。因此,您应该简单地LocalTime.parse使用:intLocalTime.of(hours, minutes)
LocalTime result = LocalTime.of(hours, minutes);
Run Code Online (Sandbox Code Playgroud)
tl;dr使用LocalTime.of(hours, minutes),这是最直接的
替代方案:用合适的解析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);
}
Run Code Online (Sandbox Code Playgroud)
输出:
09:01
Run Code Online (Sandbox Code Playgroud)