2016-11-17 92 views
0

所以我有一個字符串military time format「1532」對應於3:32 pm。 我想寫一個方法來檢查時間字符串中的每個數字是否是一個合適的數字。所以第一個元素不能大於2或等於0,等等。目前,我的代碼沒有超過第二條日誌語句,我希望你們可以幫忙!如何檢查字符串中的值?

乾杯!

String mOpen = "1532";     
Log.d("hoursTesting","pass1, length is > 2"); 
if(mOpen.getText().length() == 4) 
{ 
    Log.d("hoursTesting","pass2, length is == 4"); 
    char[] tempString = mOpen.getText().toString().toCharArray(); 
    if(tempString[0] != 0 && tempString[0] < 3) 
    { 
     Log.d("hoursTesting","pass3, first index is != 0 and < 3"); 
     if(tempString[0] == 1) 
     { 
      Log.d("hoursTesting","pass4, first index is 1"); 
      if(tempString[2] <= 5) 
      { 
       Log.d("hoursTesting","pass5, third index is <= 5, success!"); 
      } 
     } 
     else //tempString[0] is equal to 2 
     { 
      Log.d("hoursTesting","pass4, first index is 2"); 
      if(tempString[1] < 4) 
      { 
       Log.d("hoursTesting","pass5, second index is <3"); 
       if(tempString[2] <= 5) 
       { 
        Log.d("hoursTesting","pass6, third index is <= 5, success!"); 
       } 
      } 
     } 
    } 

} 
+0

您是否嘗試過調試?如果你能直觀地看到每一步發生的事情,這可能是顯而易見的。 –

+0

你需要支持閏秒嗎? – Jasen

回答

3

tempString包含字符而不是數字。 即'0'而不是0

最簡單的修復是比較字符,例如, tempString[0] == '1'或者,你可以做一些類似於int digit1 = tempString[0] - '0';的東西 - 但是那種假定你已經知道你只是在字符串中有數字。

請注意,那些聰明的ASCII傢伙的cos和他們的棘手字符集'0' < '1' < '2'等,所以你仍然可以說if (str[0] < '2')等。你只需要小心,你只是處理數字。

個人而言,我會第一個2個字符爲數字,後2個字符轉換爲數字,然後只檢查0 < = NUM​​BER1 < = 23和0 < = NUM​​BER2 < = 59

+0

是的,我有字符串中的數字,謝謝生病嘗試一下。 – TheQ

+0

但如果我想檢查char是否小於等於該值,那麼呢? – TheQ

1

你是與詮釋這裏比較CHAR:

if(tempString[0] != 0 && tempString[0] < 3) 

它應該是這樣的:

if(tempString[0] != '0' && tempString[0] < '3') 
1

我會串ŧ然後檢查每個組件是否在範圍內:

public boolean isTimeValid(String mOpen) { 
    int hours = Integer.parseInt(mOpen.substring(0, 2)); 
    int minutes = Integer.parseInt(mOpen.substring(2)); 

    if ((hours >= 0 && hours <= 24) && (minutes >= 0 && minutes <= 59)) { 
     return true; 
    } 
    else { 
     return false; 
    } 
}