We have a program that we run against our code to adhere to some coding standards.
The program says:
Expression should not be too complex, reduce the number of conditional operators used int he expression Min allowed 3.
How can I reduce the number of conditional operators? perhaps put the keyevents in an array?
public boolean onlyNumbers(KeyEvent evt) {
char c = evt.getKeyChar();
boolean returnValue = true;
if (
!(
Character.isDigit(c)
|| c == KeyEvent.VK_BACK_SPACE
|| c == KeyEvent.VK_DELETE
|| c == KeyEvent.VK_END
|| c == KeyEvent.VK_HOME
)
|| c == KeyEvent.VK_PAGE_UP
|| c == KeyEvent.VK_PAGE_DOWN
|| c == KeyEvent.VK_INSERT
) {
evt.consume();
returnValue = false;
}
return returnValue;
}
The syntax of the Java ternary operator is as follows: (condition) ? (return if true) : (return if false); You will often see the Java ternary operator symbols ( ? : ) used in texts and tutorials as an abbreviation for the construct.
In this tutorial, we will learn how to use the Greater Than or Equal To Operator in Java, with examples. The symbols used for Greater Than or Equal To operator is >= . Greater Than or Equal To operator takes two operands: left operand and right operand as shown in the following.
An Example of Conditional OperatorsThe conditional operator "&&" first evaluates whether its first operand (i.e., number % 2 == 0) is true and then evaluates whether its second operand (i.e., number % 4 == 0) is true. As both are true, the logical AND condition is true.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
final String junkChars = new String(new char[] {
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_DELETE,
KeyEvent.VK_END,
KeyEvent.VK_HOME
/* The last three seem unused in the latest version
KeyEvent.VK_PAGE_UP,
KeyEvent.VK_PAGE_DOWN,
KeyEvent.VK_INSERT */
});
if(!Character.isDigit(c) && junkChars.indexOf(c) == -1) {
evt.consume();
return false;
} else {
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With