繁体   English   中英

使用三元运算符时出错

[英]Error while using ternary operator

我正在用Eclipse Juno编写我的代码,我正在使用哈希表来设置我的dataImportObject,具体取决于其中的条目。 任何人都可以告诉我这是错的: ht是我的hashTable,其中包含<String, Integer>

(ht.containsKey("DEVICE_ADDRESS")) ? 
    dataImportObject.setDevice_Address(dataitems[ht.get("DEVICE_ADDRESS")]) : 
    dataImportObject.setDevice_Address("");

有谁能告诉我这有什么不对

两件事情:

  • 条件运算符不能单独用作语句,仅作为表达式使用
  • 我假设这些set方法具有void返回类型,因此它们不能在条件运算符中显示为操作数

三种选择:

  1. 使用if语句:

     if (ht.containsKey("DEVICE_ADDRESS")) { dataImportObject.setDevice_Address(dataitems[ht.get("DEVICE_ADDRESS")])); } else { dataImportObject.setDevice_Address(""); } 
  2. 使用条件运算符内部 setDevice_Address通话,或更清楚,事先:

     String address = ht.containsKey("DEVICE_ADDRESS") ? dataitems[ht.get("DEVICE_ADDRESS")] : ""; dataImportObject.setDevice_Address(address); 
  3. 如果您知道哈希表没有任何空值,则可以避免双重查找:

     Integer index = ht.get("DEVICE_ADDRESS"); String address = index == null ? "" : dataitems[index]; dataImportObject.setDevice_Address(address); 

您不能将三元条件的返回类型设置为void。

使用if else。

可能重复

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM