Java 如何以24小时格式输入xx:xx,而不使用“xx:&引用;犯错误?
我必须以这种格式将24小时时钟转换为分钟,同时允许用户输入他们想要的任何时间。到目前为止,我的代码只允许他们输入XX:XX,只要两个XX之间有空格,而不是冒号。我尝试过使用分隔符,但这只是最后两个XX的剪辑,它将作为分钟Java 如何以24小时格式输入xx:xx,而不使用“xx:&引用;犯错误?,java,Java,我必须以这种格式将24小时时钟转换为分钟,同时允许用户输入他们想要的任何时间。到目前为止,我的代码只允许他们输入XX:XX,只要两个XX之间有空格,而不是冒号。我尝试过使用分隔符,但这只是最后两个XX的剪辑,它将作为分钟 import java.util.*; public class TaskA { ///import the tools necessary i.e java.util.* and Scanner console. I have also used a delimi
import java.util.*;
public class TaskA {
///import the tools necessary i.e java.util.* and Scanner console. I have also used a delimiter to render the ":" as not being read.
static Scanner console = new Scanner(System.in).useDelimiter(":");
public static void main(String[] args) {
///This is how I will define the time. using both hours and minutes for the console.
int hours;
int minutes;
int total_mins;
///Here I have written how the question will come out and what the user will have to enter.
System.out.print("Specify time (HH:MM) : ");
/// Here I have the hours and minutes being inputed, as well as a draft on the final statement.
hours = console.nextInt();
minutes = console.nextInt();
///This is the mathematical equation for total minutes.
total_mins = (hours * 60) + minutes;
///final statement.
System.out.print(hours + ":" + minutes + " = " + total_mins + " Mins !");
}
}
我会把它当作一根绳子,然后把它分开
String line = console.nextLine();
hours = Integer.parseInt(line.split(":")[0]);
minutes = Integer.parseInt(line.split(":")[1]);
这是如何做到的:
String[] splitParts = console.nextLine().split(":");
if (splitParts.length >= 2)
try
{
hours = Integer.parseInt(splitParts[0]);
minutes = Integer.parseInt(splitParts[1]);
} catch (NumberFormatException e)
{
System.err.println("The entered numbers were of invalid format!");
}
else
{
System.err.println("Please enter a input of format ##:##!");
}
正如您所看到的,这段代码也处理了用户输入的危险。拆分分隔符上的字符串,您将得到两个一半。您看到我的答案了吗?看来您的代码应该按原样工作…谢谢!我已经为此强调了将近一个星期了,看到它这么容易就解决了,我感到很欣慰。最好是缓存分割的字符串:
string[]splitParts=console.nextLine().split(:”;如果(splitParts.length>=2){hours=Integer.parseInt(splitParts[0]);minutes=Integer.parseInt(splitParts[1]);}否则{/*处理无效输入*/}