我的java if语句似乎不起作用

Mat*_*son 3 java android zxing

我不知道为什么但是当我在我的Android应用程序中使用zxing来获取条形码时,格式返回为EAN_13,但是如果我不知道它不是,那么在我的Toast通知中显示EAN_13.关于它为什么破碎的任何线索?

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    if (scanResult != null) {
        if (resultCode == 0){
            //If the user cancels the scan
            Toast.makeText(getApplicationContext(),"You cancelled the scan", 3).show();
        }
        else{
            String contents = intent.getStringExtra("SCAN_RESULT");
            String format = intent.getStringExtra("SCAN_RESULT_FORMAT").toString();
            if (format == "EAN_13"){
                //If the barcode scanned is of the correct type then pass the barcode into the search method to get the product details
                Toast.makeText(getApplicationContext(),"You scanned " + contents, 3).show();
            }
            else{
                //If the barcode is not of the correct type then display a notification
                Toast.makeText(getApplicationContext(),contents+" "+format, 3).show();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Cra*_*tis 7

在Java中,您不能(嗯,不应该)使用==运算符来比较两个字符串.你应该使用:

if (stringOne.equals(stringTwo)) { ... }
Run Code Online (Sandbox Code Playgroud)

或者,在您的情况下:

if ("EAN_13".equals(format)) { ... }
Run Code Online (Sandbox Code Playgroud)

在Java中,使用对象时,double equals运算符通过引用相等性比较两个对象.如果你有两个字符串:

String one = "Cat";
String two = "Cat";
boolean refEquals = (one == two); // false (usually.)
boolean objEquals = one.equals(two); // true
Run Code Online (Sandbox Code Playgroud)

我说它通常不会是真的,因为取决于如何在系统中实现字符串的创建,它可以通过允许两个变量指向同一块内存来节省内存.但是,期望这种方法起作用的做法非常糟糕.

旁注:使用上面的策略时,你必须确保第一个String不是null,否则你将抛出一个NullPointerException.如果您能够在项目中包含外部库,我建议使用Apache Commons Lang库,它允许:

StringUtils.equals(stringOne, stringTwo);
Run Code Online (Sandbox Code Playgroud)