Question

In: Computer Science

TrackMinMax i want the generic version based on java For this lab, you will create a...

TrackMinMax
i want the generic version based on java

For this lab, you will create a generic version of the IntTrackMinMax class you wrote in a previous lab, called TrackMinMax. The API is:

Function Signature Description
constructor TrackMinMax() constructor
check void check(T i) compares i to the current minimum and maximum values and updates them accordingly
getMin T getMin() returns the minimum value provided to check() so far
getMax T getMax() returns the maximum value provided to check() so far
toString String toString() returns the string "[min,max]"
As before, your getMax() and getMin() functions may assume that check() has been called at least once. If getMin() or getMax() is called before the first call to check(), the results are undefined.

Your code will need to use the compareTo() function, so you need to be sure to limit your type parameter to only types that implement the Comparable<T> interface.

Hints

You can look at my test code by clicking "Current File" above the editing window, and selecting "TestTrackMinMax". All the test program does is read integers from standard input, and calls check() with each one. It then prints out the minimum and maximum integer that was read, and then prints the object itself (which tests toString()). For example, enter this data as the input:

0 5 -5 3 -8
When you run it with that data, it should print

Minimum: -8
Maximum: 5
[-8,5]
For grading, tour code will be tested with both Integer and String as the type parameters. If you want to test with strings in develop mode, you will need to provide the word "String" (without the quotes) as a command line parameter.

Note that because you don't know what the min/max values might be for the generic type parameter, you'll need to find some other way to initialize the min/max variables. Think about the fact that the type parameter must be a reference type, and that reference types are automatically initialized to a certain default value. You can check for that default value in your check() function to determine whether it is the first call to check(), and act accordingly.

Solutions

Expert Solution

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.


Related Solutions

JAVA Generic versions of allOf() and anyOf() In this lab, you will write generic versions of...
JAVA Generic versions of allOf() and anyOf() In this lab, you will write generic versions of the allOf() and anyOf() methods you wrote in an earlier lab. Then you will take those generic versions and create versions that work with a predicate rather than direct comparison of values. Part 1 - Create generic versions of allOf() and anyOf() Recall that the integer-only versions of allOf() and anyOf() looked like this: // Returns true if any element of 'a' is equal...
I WANT TO IMPLEMENT THIS IN JAVA PLEASE I want to create a small user input...
I WANT TO IMPLEMENT THIS IN JAVA PLEASE I want to create a small user input system for a university student, where they put the season and year of when they started their uni course. For example the system will ask "What year did you start your degree?", the user will input "Autumn/2022" as a string. Now from a string format as shown, it should take that user input and calculate for example +2 or +3 years to the date....
you will create a program with Java to implement a simplified version of RSA cryptosystems. To...
you will create a program with Java to implement a simplified version of RSA cryptosystems. To complete this project, you may follow the steps listed below (demonstrated in Java code) to guide yourself through the difficulties. Step I Key-gen: distinguish a prime number (20 pts) The generation of RSA's public/private keys depends on finding two large prime numbers, thus our program should be able to tell if a given number is a prime number or not. For simplicity, we define...
Introduction: In this project you will create a generic linked list using Java Generics. Description: Create...
Introduction: In this project you will create a generic linked list using Java Generics. Description: Create a generic class called GenLinkedList. GenLinkedList will use nodes that store a value of the generic type to store its contents. It should have the following methods. The methods should all operate on the object making the call (none are static). Perform checking of the parameters and throw exceptions where appropriate. The linked list should be singly-linked. It should not use sentinel nodes (empty...
I want you guys to rewrite this lab procedure, and it is fine if it was...
I want you guys to rewrite this lab procedure, and it is fine if it was shorter than this. An air track was fitted with two photocell bridges, one on each side of the collision region. Each bridge was operating in a gate mode timer that allows the collection of time intervals before and after collision. To ensure that friction and gravity have minimal effects, the track was leveled. Before starting the experiment, we ensured that loss in velocity was...
Having some trouble with this Java Lab (Array.java) Objective: This lab is designed to create an...
Having some trouble with this Java Lab (Array.java) Objective: This lab is designed to create an array of variable length and insert unique numbers into it. The tasks in this lab include: Create and Initialize an integer array Create an add method to insert a unique number into the list Use the break command to exit a loop Create a toString method to display the elements of the array Task 1: Create a class called Array, which contains an integer...
Android Studio (Java) I'm trying to create a simple calculator. I want to put out a...
Android Studio (Java) I'm trying to create a simple calculator. I want to put out a message if they try to divide by 0. I have this so far. What code should I put? divide.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (number1.getText().length() != 0 && number2.getText().length() != 0) { double n1= Double.parseDouble(number1.getText().toString()); double n2= Double.parseDouble(number2.getText().toString()); double res= n1 / n2; result.setText(String.valueOf(res)); } else { Toast.makeText(view.getContext(), "Please enter the numbers properly", Toast.LENGTH_SHORT).show(); } } });
WRITE A JAVA PROGRAM: For this lab, you will create a 3 x 7 two dimensional...
WRITE A JAVA PROGRAM: For this lab, you will create a 3 x 7 two dimensional array to store how many pounds of food three monkeys eats each day in a week. The 2D array is then passed to functions to find total, average and least amount of food consumption, etc. The program then need to display: the average amount of food the three monkeys ate per day the least amount of food eaten all week by any one monkey....
In java, please Create an ArrayListReview class with one data field of ArrayList with the generic...
In java, please Create an ArrayListReview class with one data field of ArrayList with the generic type passed to the class. (1 point) Create a constructor that populate an array list filled with the generic type through inserting new elements into the specified location index-i in the list. (1 point) Implement mergeSort using a list and recursion. (2 points) Write the main method to test your program and use System.nanoTime() to find out the speed of each step of your...
I. At the beginning, create a folder named "test" and add the folder into the version...
I. At the beginning, create a folder named "test" and add the folder into the version control tool tracking system. Then create one file named "001" under this folder. Commit any change if necessary. II. Next, add another file named "002" in the same folder and commit the change ("adding") in the version control tool. III. Followed by adding that file, create a branch (namely, "branch-A") in the version control tool and make some changes to the contents in file...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT