2013-11-01 4 views
4

나는 막 떠오 릅니다. 어쩌면 12 시간 동안 일했기 때문일 수도 있습니다.하지만 실행하는 경우 내 if 문장이 true로 평가되지 않는 이유는 무엇입니까? if (band.equals("4384") ?? 화면에 band을 인쇄 중이며 4384을 읽었지만 실제로는 평가되지 않습니다. .equals()를 너무 자주 사용하여 문제가 발생했습니다. 무엇을 잘못 했습니까?간단한 string.equals() 문이 작동하지 않는 경우 Java

public class Test { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     String endBand = " "; 

     String str = "SCELL: UARFCN 4384, Prim. SC: 362, RSCP: 70, EcNo: 44"; 

     endBand = getBandNumber(str); 

     System.out.println("endBand is " + endBand); 

    } 

    // ************************************************ 
    // Returns the current band that the device is on. 
    // Currently only coded for 3G 
    // ************************************************ 
    private static String getBandNumber(String str) { 

     // The string returned to str will be in the form of: 
     // "SCELL: UARFCN 4384, Prim. SC: 362, RSCP: 73, EcNo: 33" 
     // ^^^^ 
     // String str = read_AT("AT+XL1SET=\"IRATSCEL?\"", 10); 

     String band = " "; 
     int begin = 0, end = 0; 

     // Filter through the string to extrace the channel number 
     for (int i = 0; i < str.length(); i++) { 

      char c = str.charAt(i); 

      if (c == 'N' && str.charAt(i + 1) == ' ') { 

       begin = i + 1; 

      } else if (c == ',') { 

       end = i; 

       break; 

      } 

     } 

     band = str.substring(begin, end); 
     System.out.println("band is " + band); 

     if (band.equals("4384")) { 

      band = "5"; 

     } else { 

      band = "2"; 
     } 

     return band; 

    } 

} 

답변

6

당신은 다음과 같이 인쇄 4384. 시도의 앞 밴드 변수에 공백이 있습니다 평가에

System.out.println("band is '" + band + "'"); 
+1

주 ends-- 예기치 않은 공백을 볼 수 있습니다. 이것은 유용한 패턴입니다! (또한, 연결 대신 문자열 형식을 사용하십시오. 훨씬 깔끔합니다.'String.format ("band is '% s'", band)') –

+0

고마워. 나는 그 공간을 포함하고 있다는 것을 깨닫지 못했습니다. – Ducksauce88

7

을, 당신은 (" 4384"에 eqaul actaully하는 문자열과 함께 종료된다 공간을 주목하라).

사용해보십시오 ...

if (band.trim().equals("4384")) {... 

대신

+0

나는 이것을 지금부터 실제로 사용할 것이라고 생각한다. 그래서 나는 공간을 들여다 보지 않을 것이다. – Ducksauce88

+0

'band'가'null'이 아닌지 확인하고 있는지 확인하십시오;) – MadProgrammer

1

보십시오 : 그것은 시작 어디에`band` 변수 주위에 작은 따옴표가 당신을 보여

// Filter through the string to extrace the channel number 
    for (int i = 0; i < str.length(); i++) { 

     char c = str.charAt(i); 

     if (c == 'N' && str.charAt(i + 1) == ' ') { 

      begin = i + 2; //i + 2 

     } else if (c == ',') { 

      end = i; 

      break; 

     } 

    }