[英]My java if statement doesn't seem to be working
我不知道為什么但是當我在我的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);
當你使用==
你要比較兩個引用,看它們是否是同一個對象(即它們指向內存中的相同地址),而不是比較對象的值。 請改用format.equals("EAN_13")
。
對於String比較,你應該使用.equals()方法,實際上這是對兩個對象進行比較,而這個方法在java中屬於Object類。 例如:
String val = "abc";
if(val.equals("abc")){
System.out.println("stings are equal!");
}
另一方面,您可以在Comparable接口中使用.compareTo()函數,eq:
String val = "abc";
if(val.compareTo("abc")==0){
System.out.println("stings are equal!");
}
**這與上述相同
在java中,你不能將String與==
進行比較,所以請用.compareTo("str")
或.equals()
方法替換這些運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.