I wanted to know if there was a way to shorten this if statement with the “.equals” so that I can test things in one line, instead of multiple if statements.
This is an excerpt my current long winded code. (This is what I want to shorten)
if (queryArray[1].equals("+")) {
System.out.println("Got +");
} else if (queryArray[1].equals("-")) {
System.out.println("Got -");
} else if (queryArray[1].equals("*")) {
System.out.println("Got *");
}
I tried doing this (Does not work) to reduce the number of lines needed.
if (queryArray[1].equals("+","-","*")) {
System.out.println("Got +");
}
And even (Does not work):
if (queryArray[1].equals("+" || "-" || "*")) {
System.out.println("Got +");
}
Also, I know about the or syntax “||” within if statements, however I’m looking to shorten it within the “.equals()” method.
Is there any way to shorten this code? Thank you.
Since you’re only doing single-character comparisons, you can do a
switchonqueryArray[1].charAt(0).Or if you’re using Java 7, you can switch directly on the string.