Java 嵌套的if-else语句被跳过且不执行任何操作
我正在做一个应用程序,其中的代码将扫描条形码,并检查内容,如果内容与if-else语句相符,它将显示价格。我如何解决这个问题 代码如下:Java 嵌套的if-else语句被跳过且不执行任何操作,java,android,android-layout,if-statement,barcode,Java,Android,Android Layout,If Statement,Barcode,我正在做一个应用程序,其中的代码将扫描条形码,并检查内容,如果内容与if-else语句相符,它将显示价格。我如何解决这个问题 代码如下: public class barcode extends AppCompatActivity { Button scan_btn; EditText Edit_current; TextView formatTxt, contentTxt,price; int x; @Override protected vo
public class barcode extends AppCompatActivity {
Button scan_btn;
EditText Edit_current;
TextView formatTxt, contentTxt,price;
int x;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_promotion_page);
formatTxt = (TextView) findViewById(R.id.scanFormat);
contentTxt = (TextView) findViewById(scanContent);
price = (TextView)findViewById(R.id.Price);
scan_btn = (Button) findViewById(R.id.scan_button);
final Activity activity = this;
scan_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.PRODUCT_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result.getContents( ) == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else if (result.getContents().equals(12345014)){
price.setText("$999");
}else if (result.getContents().equals(12345021)){
price.setText("$91");
}
}}
由于可用信息有限,我认为这是因为
result.getContents()
与您正在检查的任何语句都不匹配。我想在底部加上这句话作为最后的陈述:
} else {
Log.d("MainActivity", "Failed to match. Contents are " + result.getContents());
}
因此,至少您可以看到
result.getContents()
包含的内容,并可以相应地采取行动。您当前的解决方案也不是很具有可扩展性-我会考虑使用switch
语句或使用SQLite查询产品数据库。您想了解switch语句;以及如何将它们与字符串一起使用。由于您指定的3个条件均未满足,因此将跳过该选项。因此result.getContents()既不为null,也不等于12345014或12345021。首先,您需要调试getContents()方法返回的内容,正如@AbdulWaheed所说的,请尝试记录result.getContents()
。另外,在您的情况下,切换case语句时默认使用“Item not found”会更好,添加新项也会更容易。在您的情况下,尝试添加一个else块,使用price.setText(“Item not found!”)
当我调试时,setText没有被调用。添加了这个,即使我扫描内容,它也没有显示任何内容,这意味着onActivityResult()
根本没有被调用。你能在activityResult()的顶部粘贴一行日志
来确保这一点吗?