Thursday, September 10, 2009

lab 05 using only 2 comparisons

import java.util.Scanner;
public class lab05demo {
 /**
  * Another solution I mentioned in the lab
  * xusun09@gmail.com
  */
 public static void main(String[] args) {

  Scanner reader = new Scanner(System.in);
  String s1 = reader.next();
  String s2 = reader.next();
  String s3 = reader.next();
  
  if ((s1.compareTo(s2)>=0&&0>=s1.compareTo(s3))||(s1.compareTo(s2)<=0&&0<=s1.compareTo(s3)))
  {
   System.out.println(s1);
  }
  else if ((0>=s1.compareTo(s2)&&s1.compareTo(s2)>=s1.compareTo(s3))||
           (0<=s1.compareTo(s2)&&s1.compareTo(s2)<=s1.compareTo(s3)))
  {
   System.out.println(s2);
  }
  else System.out.println(s3);
 }
}

1 comment:

jmvidal said...

As I mentioned in class, this program would be easier to understand if you do not use the cmp1 and cmp2 variables and instead use s1.compareTo(s2) and s1.compareTo(s3) every time.

That might seem slower to you because you are calling the same functions twice, but rest assured the compiler is smart enough to optimize that for you. Premature optimization is the root of all evil.

If you really feel you HAVE to use those temporary variables, you should at least given them better names, like s1ComparedToS2 instead of cmp1.

Anyway, the program does work, which is by far the most important thing. Good job!