按照你的格式,用戶必須輸入與時間 ':' 在第三個字符位置charAt(2)
和其餘字符(索引0,1,3和4)必須是數字。一個非常快速實施和良好的學習解決方案是使用正則表達式:http://www.regular-expressions.info/tutorial.html
不過,我會向您展示一個簡單的使用你的代碼爲模板,瞭解解決方案:
- 驗證長度在5
- 驗證時間是正確的
- 確認分鐘是正確的
- 詢問用戶如果有什麼不正確,重新輸入值
下面的代碼:
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();
boolean correctFormat = false;
int hour = 0, minute = 0;
while (!correctFormat) {
correctFormat = true;
if (time.length() != 5)
correctFormat = false;
else {
// Get the value before the ':'
hour = Integer.parseInt(time.substring(0, 2));
if (hour >= 24 || hour < 0)
correctFormat = false;
// Get the value after the ':'
minute = Integer.parseInt(time.substring(3, 5));
if (minute >= 60 || minute < 0)
correctFormat = false;
}
if (!correctFormat) {
System.out.print("Pleaase follow the format! Enter the time in HH:MM :");
time = T.next();
}
}
// Formula of the calculation
total = hour * 60 + minute;
// Display the final value
System.out.println(time + " is " + total + " minutes.");
此外,如果你想更強大的代碼,你可以檢查,如果用戶之前和之後的實際進入數字「:」通過捕捉一個「NumberFormatException異常'如果參數不是實際的數字,將從Integer.parseInt()
方法拋出。
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();
boolean correctFormat = false;
int hour = 0, minute = 0;
while (!correctFormat) {
correctFormat = true;
if (time.length() != 5)
correctFormat = false;
else {
try {
hour = Integer.parseInt(time.substring(0, 2));
minute = Integer.parseInt(time.substring(3, 5));
} catch (NumberFormatException e) {
correctFormat = false;
}
if (correctFormat) {
if (hour >= 24 || hour < 0)
correctFormat = false;
if (minute >= 60 || minute < 0)
correctFormat = false;
}
}
if (!correctFormat) {
System.out.print("Pleaase follow the format! Enter the time in HH:MM :");
time = T.next();
}
}
// Formula of the calculation
total = hour * 60 + minute;
// Display the final value
System.out.println(time + " is " + total + " minutes.");
[常規匹配HH表達:MM時間格式]的可能的複製:(http://stackoverflow.com/questions/7536755/regular-expression-可以通過編輯上述代碼,以如下這樣做for-matching-hhmm-time-format) – Thevenin
你現在不會想要一個24:53的時間,是嗎?那麼爲什麼<= 24而不是<24?另外,是否允許一位數的小時? – laune
對不起<=我的錯誤,但格式必須是hh:mm。 – Flipz