Showing posts with label equal to 4 5 6. Show all posts
Showing posts with label equal to 4 5 6. Show all posts

Wednesday, April 20, 2011

Checking if i=4 or 5 or 6 in single if condition without using logical operators

I tried and found two solutions. One is mathematical and other one is just a java trick.

Mathematical solution:


public class Test1 {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
if((i-4)*(i-5)*(i-6) == 0 ){
System.out.println("4<=i<=6");
}else{
System.out.println("i!=4or5or6");
}
}
}


Other solution is bit tricky:


public class Test2 {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
if("4,5,6".indexOf(String.valueOf(i)) >=0){
System.out.println("4<=i<=6");
}else{
System.out.println("i!=4or5or6");
}
}
}