In: Computer Science
1. Write a class Compare3 that provides a static method largest.
Method largest should take three Comparable parametersand return
the largest of the three (so its return type will also be
Comparable). Recall that method compareTo is part ofthe Comparable
interface, so largest can use the compareTo method of its
parameters to compare them.
2. Write a class Comparisons whose main method tests your largest
method above.
• First prompt the user for and read in three strings,
use your largest method to find the largest of the three strings,
andprint it out. (It’s easiest to put the call to largest directly
in the call to println.) Note that since largest is a staticmethod,
you will call it through its class name, e.g.,
Compare3.largest(val1, val2, val3).
• Add code to also prompt the user for three integers
and try to use your largest method to find the largest of the
threeintegers. Does this work? If it does, it’s thanks to
autoboxing, which is Java 1.5’s automatic conversion of ints
toIntegers. You may have to use the -source 1.5 compiler option for
this to work.
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.util.Scanner;
public class Comparisons {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three integes: ");
int val1 = sc.nextInt();
int val2 = sc.nextInt();
int val3 = sc.nextInt();
System.out.println("Largest: "+Compare3.largest(val1, val2, val3));
}
}
class Compare3{
public static Comparable largest( Comparable val1, Comparable val2, Comparable val3){
// getting largest between val1 and val2
Comparable largest = val1.compareTo(val2) > 0 ? val1 : val2;
// getting largest between val1, val2, val3
largest = largest.compareTo(val3) > 0 ? largest : val3;
return largest;
}
}
/*
Sample run:
Enter three integes: 89 23 90
Largest: 90
*/