加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 05:07:29 所属栏目:Java 来源:网络整理
导读:我不知道为什么但是当我在我的 Android应用程序中使用zxing来获取条形码时,格式返回为EAN_13但是我的if staement决定它不是,然后在我的Toast通知中显示EAN_13.关于它为什么破碎的任何线索? public void onActivityResult(int requestCode,int resultCode,In
我不知道为什么但是当我在我的 Android应用程序中使用zxing来获取条形码时,格式返回为EAN_13但是我的if staement决定它不是,然后在我的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();
            }
        }
    }
}

解决方法

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

if (stringOne.equals(stringTwo)) { ... }

或者,在您的情况下:

if ("EAN_13".equals(format)) { ... }

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

String one = "Cat";
String two = "Cat";
boolean refEquals = (one == two); // false (usually.)
boolean objEquals = one.equals(two); // true

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

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

StringUtils.equals(stringOne,stringTwo);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读