1

So, I know you can't use a variable in the case statement. I am hoping someone can point me to code that would be fairly efficient as a replacement. (I could do a bunch of ifs, for example).

The situation is that I have an array of object data, and I want to iterate through that array. The position in the array is given by a name as shown below (the int...ordinal statements). Basically I have to assign generate 'result' objects for certain members of the array (if they are discrete data such as C_VENT_RATE). The only way I can see this done easily is do a bunch of ifs such as if (i.equals(pr_int)).

  ArrayList<String[]> rawEKGs  = ekgFile.getForMrno( docInfo.getMedicalRecordNumber() );

  for (String[] parts : rawEKGs) {
    for (int i=0; i< parts.length; i++ )
    {
      Result result = docInfo.getResult();
      boolean process = true;
      final int vent_rate = UncEKG.COL_NAMES.C_VENT_RATE.ordinal();
      int art_rate = UncEKG.COL_NAMES.C_ART_RATE.ordinal();
      int pr_int = UncEKG.COL_NAMES.C_PR_INTERVAL.ordinal();
      int qrs_dur =  UncEKG.COL_NAMES.C_QRS_DURATION.ordinal();
      int qt_qtc =  UncEKG.COL_NAMES.C_QT_QTC.ordinal();
      int prt =  UncEKG.COL_NAMES.C_PRT_AXES.ordinal();


      switch(i) {
        case : // something
          break;
        default: process = false;
      }
4

4 回答 4

4

由于您已经有一个枚举,您可以尝试Command使用 EnumMap 将您的枚举映射到命令的模式。

每个Command实例都将与您的一个案例语句具有相同的逻辑。

EnumMap<UncEKG.COL_NAMES, Command> map = ...
//values is in ordinal order
//pulled out for performance reasons
UncEKG.COL_NAMES[] names = UncEKG.COL_NAMES.values();
for (String[] parts : rawEKGs) {
    for (int i=0; i< parts.length; i++ ){
       map.get(names[i]).execute();
    }
}
于 2013-10-01T21:00:05.407 回答
1

如果对象包含一个枚举(UncEKG)作为变量,为什么不直接使用枚举上的开关

switch (theEnum) {
    case UncEKG.COL_NAMES.C_VENT_RATE:
        //something
        break;
    case UncEKG.COL_NAMES.C_PR_INTERVAL:
        //something else
        break;
    default: process = false
}

枚举信息

于 2013-10-01T20:58:10.480 回答
1

我认为正确的方法是将逻辑放在枚举中。因此,您将向枚举类添加一个静态方法以根据 int 获取正确的列,然后您可以根据枚举进行切换,或者可能做其他事情,或者甚至更好地在枚举上设置一个方法来说明是否列是否被处理(尽管如果枚举更通用,这可能不合适)。

不过,又快又脏看起来像这样:

 ArrayList<String[]> rawEKGs  = ekgFile.getForMrno( docInfo.getMedicalRecordNumber() );
 UncEKG.COL_NAMES[] values = UncEKG.COL_NAMES.values();
 for (String[] parts : rawEKGs) {
    for (int i=0; i< parts.length; i++ )
    {
       Result result = docInfo.getResult();
       boolean process = true;
       switch (values[i]) {
           case UncEKG.COL_NAMES.C_VENT_RATE:
                break;
           default: process = false;
       }
    }
 }
于 2013-10-01T20:58:22.553 回答
1

喜欢这种方式

    switch(i) {
        case 0: // something
          break;
        case 1: // something
          break;
        case 2: // something
          break;
         .
         .
         .
         .
        default: process = false;
      }
于 2013-10-01T20:47:27.260 回答