简单的string.equals()如果语句不能正常工作Java

时间:2013-11-01 01:00:28

标签: java string equals

我快要疯了。也许这是因为我已经工作了12个小时......但是为什么我的if语句在运行if (band.equals("4384")时没有评估为真?我正在将band打印到屏幕上,它正在读取4384,但它不会评估为true。我已经多次使用.equals()而没有问题,我做错了什么?

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;

    }

}

3 个答案:

答案 0 :(得分:7)

你的乐队变量在4384前面有一个空格。试着像这样打印:

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

答案 1 :(得分:7)

经过评估,您最终会得到一个实际上等于" 4384"的字符串(请注意空格)。

尝试使用...

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

相反

答案 2 :(得分:1)

尝试:

 // 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;

        }

    }