温馨提示×

java输入时间的形式如何输入

小亿
122
2023-09-28 03:36:26
栏目: 编程语言

在Java中,可以使用Scanner类来接收用户的时间输入。以下是一个示例代码片段,演示如何接收用户输入的时间。

import java.util.Scanner;
public class TimeInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入时间(格式为HH:mm:ss):");
String timeString = scanner.nextLine();
try {
String[] timeParts = timeString.split(":");
int hours = Integer.parseInt(timeParts[0]);
int minutes = Integer.parseInt(timeParts[1]);
int seconds = Integer.parseInt(timeParts[2]);
System.out.println("您输入的时间是:" + hours + "时" + minutes + "分" + seconds + "秒");
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
System.out.println("输入的时间格式不正确");
}
scanner.close();
}
}

运行以上代码,将提示用户输入时间,并按照“小时:分钟:秒钟”的格式输入。然后,程序将解析用户输入的时间,并打印出各个时间部分的值。

注意:上述代码只是一个简单示例,没有进行严格的输入验证和错误处理。在实际的应用程序中,您可能需要添加更多的验证和错误处理逻辑,以确保用户输入的时间格式正确。

0