gpt4 book ai didi

java - 如何验证此 Java 代码的用户输入?

转载 作者:行者123 更新时间:2023-12-01 10:58:36 25 4
gpt4 key购买 nike

我想验证以下内容:仅输入数字,小时必须 <=24,分钟必须 <60,并且用户必须在 hh:mm 之间键入“:”符号。

 int total; //Total Minutes
String time; //Input from keyboard


final Scanner T = new Scanner(System.in);

System.out.print("Enter the time in HH:MM :");
time = T.next();

//Get the value before the ':'
int hour = Integer.parseInt(time.substring(0, time.indexOf(':')));


//Get the value after the ':'
int minute =Integer.parseInt (time.substring((time.indexOf(':') + 1), time.length()));


//Formula of the calculation
total = hour * 60 + minute;


//Display the final value
System.out.println( time +" is " + total + " minutes.");

最佳答案

要进行验证,请使用正则表达式:

time.matches( "(?:[01][0-9]|2[0-3]):[0-5][0-9]" )

要转换,只需使用

int hour = Integer.parseInt(time.substring(0, 2));
int minute = Integer.parseInt(time.substring(3));

关于java - 如何验证此 Java 代码的用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33466016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com