o the user's text. The length is retrieved
* from the rotation length field, and the user's text is retrieved from the
* text area.
*
* @author Thornton Rose
*/
private void applyRotAscii() {
int rotLength = 0; // rotation length
RotAscii cipher = null; // ASCII rotation cipher
try {
// Get rotation length field and convert to integer.
rotLength = Integer.parseInt(rotationLengthField.getText().trim());
// Create ASCII rotation cipher and transform the user's text with it.
cipher = new RotAscii(rotLength);
textArea.setText(cipher.transform(textArea.getText()));
} catch(Exception ex) {
// Report the exception to the user.
ExceptionDialog.show(this, "Invalid rotation length: ", ex);
}
}
块和语句
使用下面的方针来编写块和语句:
一行只写一个语句
控制语句总是使用{}这样的括号 (e.g., 'if').
考虑在块的末尾使用一个注释 (e.g., } // end if), 尤其是长的或嵌套块
在块的开头放置变量的声明语句
总记得初始化变量
如果你是个完美主义者,左对齐变量名
在switch块里缩进case从句
在操作符后留有空白
在if, for, 或while语句中, 在括号“(”前留有空白
在表达式中使用空白和插入语来增强可读性
在for循环中的变量是个例外。 循环变量可能会在语句初始化部分被定义。 e.g., for (int i = 0; ...)
.
在块的末尾插入注释有助于你无意中跟踪到被删除的结尾括
号“}”.
Example 3. Bad Block Style.
try{
for(int i=0;i<5;i++){
...
}
int threshold=calculateThreshold();
float variance=(threshold*2.8)-1;
int c=0;
if (threshold<=15) c=calculateCoefficient();
switch(c){
case 1: setCeiling(c*2); break;
case 2: setCeiling(c*3); break;
else: freakOut();
}
}catch(Exception ex){ ... }
Example 4. Good Block Style.
try {
int threshold = 0;
float variance = 0.0;
int coefficient = 0;
// Prepare 5 cycles.
for (int i = 0; i < 5; i ++){
prepareCycle(i);
}
// Calculate the threshold and variance.
threshold = calculateThreshold();
variance = (threshold * 2.8) - 1;
// If the threshold is less than the maximum, calculate the coefficient.
// Otherwise, throw an exception.
if (threshold <= MAX_THRESHOLD) {
coefficient = calculateCoefficient();
} else {
throw new RuntimeException("Threshold exceeded!");
}
// Set the ceiling based on the coefficient.
switch (coefficient) {
case 1:
setCeiling(coefficient * 2);
break;
case 2:
setCeiling(coefficient * 3);
break;
else:
freakOut();
} // end switch
} catch(Exception ex) {
...
} // end try
Translated by Willpower,2003.11.17