Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Expression too complex reduce the number of conditionl operators

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;
}
like image 439
user1158745 Avatar asked Jan 08 '15 17:01

user1158745


People also ask

What is the use of '?' In Java?

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.

Can you do >= in Java?

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.

What is conditional operator with example?

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.

What is the symbol for ternary operator in Java?

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.


1 Answers

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;
}
like image 195
Dima Avatar answered Oct 06 '22 01:10

Dima