2016-11-17 96 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; 
    } 
}