In: Computer Science
TrackMinMax.java (code to copy)
//declare generic classs whose elements are of comparable type
class TrackMinMax<T extends Comparable<T>>{
//declare member variables to store current min and max
private T cur_min;
private T cur_max;
//this variable tells if the check function has been called once or not
private static boolean is_checked = false;
//constructor
public TrackMinMax(){}
//this method updates cur_min and cur_max
public void check(T i){
//if the method has never been called, directly update min and max values
if(!is_checked){
is_checked=true;
cur_min=i;
cur_max=i;
}else{
//update cur_min
if(cur_min.compareTo(i)>0){
cur_min=i;
}
//update cur_max
if(cur_max.compareTo(i)<0){
cur_max=i;
}
}
}
//member variable to get cur_min
public T getMin(){
return cur_min;
}
//member variable to get cur_max
public T getMax(){
return cur_max;
}
//member variable to print the object
public String toString(){
return "["+cur_min+","+cur_max+"]";
}
}
TrackMinMax.java (code screenshot)
Test.java (code to copy)
import java.util.*;
import java.text.*;
class Test{
public static void main(String[] args) throws Exception{
//create Scanner object to read from the user
Scanner sc = new Scanner(System.in);
//read a line
String input = sc.nextLine();
//store this line in the scanner so that we can read numbers/string separated by spaces
sc = new Scanner(input);
//check if command line argument was provided and the value was String
if(args.length==1 && args[0].equals("String")){
//we have to implement string version of the program
TrackMinMax<String> tmm = new TrackMinMax<String>();
//variable to store each word
String val;
//read until line ends
while(sc.hasNext()){
//read next words
val=sc.next();
//call check method
tmm.check(val);
}
//print the result in the format given in the problem statement
System.out.println("Minimum: "+tmm.getMin());
System.out.println("Maximum: "+tmm.getMax());
System.out.println(tmm);
}else{
//we have to implement integer version of the program
TrackMinMax<Integer> tmm = new TrackMinMax<Integer>();
//variable to store each integer
Integer val;
//read until line ends
while(sc.hasNextInt()){
//read next integer
val=sc.nextInt();
//call check method
tmm.check(val);
}
//print the result in the format given in the problem statement
System.out.println("Minimum: "+tmm.getMin());
System.out.println("Maximum: "+tmm.getMax());
System.out.println(tmm);
}
}
}
Test.java (code screenshot)
Sample Input/Output Screenshot 1 when called like - java Test
Sample Input/Output Screenshot 2 when called like - java Test String
Let me know in the comments if you have any doubts.
Do leave a thumbs up if this was helpful.