新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

java输入时间的形式如何输入,java输入时间年月日时分秒

发布时间:2023-09-28 03:36:26

java输入时间的情势如何输入

在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();
}
}

运行以上代码,将提示用户输入时间,并依照“小时:分钟:秒钟”的格式输入。然后,程序将解析用户输入的时间,并打印出各个时间部份的值。
注意:上述代码只是一个简单示例,没有进行严格的输入验证和毛病处理。在实际的利用程序中,您可能需要添加更多的验证和毛病处理逻辑,以确保用户输入的时间格式正确。