2014-02-09 2 views
1

주어진 우편 번호 (우편 번호)가 주어진 우편 번호 2 개 범위에 있는지 알아보기 위해 if 문을 작성하려고합니다. 우편에 대한문자열이 지정된 문자열의 범위에 있는지 찾는 방법

public boolean postCodeInRange(String postCode, String zone) 
{ 
    if (zone.charAt(0)==postCode.charAt(0)) 
    { 
     if ((int) postCode.charAt(1) >= (int) zone.charAt(1) && 
      (int) postCode.charAt(1) <= (int) zone.charAt(5) && 
      (int) postCode.charAt(2) >= (int) zone.charAt(2) && 
      (int) postCode.charAt(2) <= (int) zone.charAt(6)) 

      return true; 
    } 
    return false; 
} 

이 유일한 작품 :

예를 들어, 나는 J8Q (이 경우에는)

내가 이것을 쓴 J8P-J9A의 범위에있는 경우 찾는 방법을 알고 싶어요 과 같은 코드는 L0A-L9Z 범위에 있습니다.

+0

그리고 그것은 어떤 다른 범위를 지원해야? –

답변

0

간단한 해결책 :

public boolean postCodeInRange(String postCode, String zone) { 
    return postCode.compareTo(zone.substring(0, 3)) >= 0 
     && postCode.compareTo(zone.substring(4)) <= 0; 
} 
1

compareTo 메서드는 두 문자열 사이의 첫 번째 다른 문자의 차이점을 반환합니다. 우편 번호가 항상 문자 - 숫자 - 글자인지 확실하지 않지만,이 경우 작동해야합니다. 그렇지 않은 경우 문제에 맞게 컴파 이터가 필요할 수 있습니다.

기본적으로 입력 문자열이 다른 두 문자열 사이에 있는지 확인해야합니다.

if(minPostCode.compareTo(input) <= 0 && maxPostCode.compareTo(input) >= 0) { 
    //it is between two post codes 
} 
0

if 문이 잘못되었습니다. 다음과 같이해야합니다.

public boolean postCodeInRange(String postCode, String zone) 
{ 
    if (zone.charAt(0)==postCode.charAt(0)) 
    { 
     if ((int) postCode.charAt(1) < (int) zone.charAt(1) || 
      (int) postCode.charAt(1) > (int) zone.charAt(5) 
      return false; 
     if (((int) postCode.charAt(1) == (int) zone.charAt(1) && 
      (int) postCode.charAt(2) < (int) zone.charAt(2)) || 
      ((int) postCode.charAt(1) == (int) zone.charAt(5) && 
      (int) postCode.charAt(2) > (int) zone.charAt(2))) 
      return false; 
     return true; 
    } 
    return false; 
} 

위와 같이 읽기는 어렵지만 편집하기가 더 어렵습니다. 더 나은 솔루션은 다음과 같습니다

public boolean postCodeInRange(String postCode, String zone) 
{ 
    String minCode = zone.substring(0, 3); 
    String maxCode = zone.substring(4, 7); 
    return minCode.compareTo(postCode) <= 0 && postCode.compareTo(maxCode) <= 0; 
} 
관련 문제