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");
}
}
}

9 comments:

  1. what is the definition of logical operators?

    what are "==" and ">=" then? are they also logical operators:-)))

    ReplyDelete
  2. No they are not they are relational operators.

    ReplyDelete
  3. I liked the first one, simple but clever. This has given me another idea !!!

    ReplyDelete
  4. It can be done this way as well:
    public class Test3 {
    {
    public static void main(String[] a)
    {
    int i=Integer.parseInt(a[0]);
    if("456".contains(""+i+"")) {
    System.out.println(i+" is 4,5or6");
    }
    else {
    System.out.println(i+" is not 4,5or6");
    }
    }
    }

    ReplyDelete
  5. I think Kulbeer's solution fails if we pass 56 or 45. It returns true in these cases also. But it should be checking only 4 or 5 or 6 right?

    ReplyDelete
  6. You are right.. even it will not work for 456 also.. His solution can be made right if

    "456".contains(""+i+"") is replaced with
    "4,5,6".contains(""+i+""

    you can check that

    ReplyDelete