2015-11-02 59 views
0

我必須將這種格式的24小時制轉換爲分鐘,同時允許用戶輸入他們想要的任何時間。到目前爲止,我的代碼只允許他們進入XX:XX,只要兩個XX之間有一個空格,而不是冒號。我曾嘗試使用分隔符,但只是最後兩個XX將作爲分鐘的剪輯。如何以24小時格式輸入xx:xx而不顯示「:」給出錯誤?

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 !"); 
    } 
} 
+0

在分隔符上分割字符串,您將擁有兩個部分 – Whymarrh

+0

你見過我的答案嗎?看起來你的代碼應該按原樣工作... – janos

回答

0

我會把它當作一個字符串,然後分割它。

String line = console.nextLine(); 
hours = Integer.parseInt(line.split(":")[0]); 
minutes = Integer.parseInt(line.split(":")[1]); 
+0

謝謝!近一週來,我一直在強調這一點,看到它解決得如此簡單,我感到欣慰。 –

+0

緩存splitted字符串會更好:'String [] splitParts = console.nextLine()。split(「:」); if(splitParts.length> = 2){hours = Integer.parseInt(splitParts [0]);分鐘= Integer.parseInt(splitParts [1]); } else {/ *處理無效輸入* /}' – RAnders00

0

這是它是如何做:

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 ##:##!"); 
} 

該代碼處理用戶輸入的危險,以及,你可以看到。

相關問題