2011-03-01 108 views
1
public final byte[] getParam(String commandName,String memLocation,String dataId){ 
    byte[] result = new byte[9]; 
    result[0] = START_FRAME.getBytes()[0]; 
    result[1] = START_FRAME.getBytes()[0]; 
    result[2] = Integer.toHexString(commandMap.get(commandName)).getBytes()[0]; 
    result[3] = Integer.toHexString(dataIdMap.get(dataId)).getBytes()[0]; 
    result[4] = Integer.toHexString(locationMap.get(memLocation)).getBytes()[0]; 

    result[5] = Integer.toHexString(commandMap.get(commandName) + dataIdMap.get(dataId) + locationMap.get(memLocation)).getBytes()[0]; 

    result[6] = END_FRAME.getBytes()[0]; 
    result[7] = END_FRAME.getBytes()[0]; 
    result[8] = END_OF_LINE.getBytes()[0]; 
    //Check sum -> {{d10d}} 
    return result; 
} 

如何減少的結果[5]除了值的函數調用...減少代碼..起作用

可以我通過這樣?

public static final byte[] createCheckSum(byte[] paramsToBeAdded){ 
      byte[] result = paramsToBeAdded; 
      ............ 
      ........... etc 
    return result[0] + result[2]; 
} 

正確答案:

private String createCheckSum(byte[] byteHolder,int startIndex,int endIndex){ 
    byte[] byteToCompute = byteHolder;  
    int sum = 0;  
for(int i=startIndex; i<=endIndex; i++){  
     sum += Integer.valueOf(byteToCompute[i]);  
}  
return Integer.toHexString(sum);  
}  
+1

您確定只需要添加該函數嗎?對於通用功能,通常功能將更爲明智。如果可以說,如果你有重複的代碼,你想放在一個函數中,它會對你更有用。 – bits 2011-03-01 06:38:49

+0

嗯...我可以沒有它...但我會在整個項目中有這樣的補充..是啊..你是對的... – 2011-03-01 06:42:15

+0

啊,這是一個測試。我已更正(格式化)您的正確答案。但是,說實話,我沒有看到你的正確答案與你正確的問題相符......最初你問了一個方法的建議,把某些東西分配給'result [5]'。您的正確答案甚至不使用代碼片段中的變量。 – 2011-03-01 09:23:27

回答

1

看起來使用一些類的成員變量的等。在這種情況下,一個功能將使代碼的可讀性更強一點(選擇顯示了該方法是做一個好名字):

private String computeSomething(String commandName,String memLocation,String dataId) { 
    int commandValue = commandMap.get(commandName); 
    int dataValue = dataIdMap.get(dataId); 
    byte memValue  = locationMap.get(memLocation)).getBytes()[0]; 
    return Integer.toHexString(commandValue + dataValue + memValue); 
} 

調用它像這樣:

result[5] = computeSomething(commandName, memLocation, dataId); 

(和替換名稱computeSomething可讀性效果

+0

private String createCheckSum(byte [] byteHolder,int startIndex,int endIndex){ \t byte [] byteToCompute = byteHolder; \t int sum = 0; \t for(int i = startIndex; i <= endIndex; i ++){ \t \t sum + = Integer.valueOf(byteToCompute [i]); \t} return Integer.toHexString(sum); } – 2011-03-01 08:57:30