Question

In: Computer Science

Please use Java only. Write the class TopResult, which keeps track of the best (highest numbered...

Please use Java only.

Write the class TopResult, which keeps track of the best (highest numbered or highest ordered) result it has seen so far. The class will be a generic type, so the type of results it sees depends on how it is declared.

TopResult Task:

There are a number of situations in which we want to keep track of the highest value we've seen so far - a highest score, a most recent entry, a name which is closest to the end (or the front) of a list, etc. We can imagine writing a simple class which will do this: a class which will let us enter new results one by one, and at any point will let us stop and ask for the highest value.

So far, so good, right? But what if we have a number of different applications for this sort of class - for example, we want to find the top (integer) score on a test, or the highest (decimal) temperature reading, or the GUI window which is closest to the top, etc. Subclassing isn't quite the way to go here, because a TopResult which holds Integers isn't an instance of a TopResult which holds Doubles, and vice versa. But simply writing a class for every possible type we may need may seem like overkill, since the structure of the code is essentially the same from class to class.

In situations such as these, generics come to our rescue. When we define a generic class, the data type we use is essentially represented as a wildcard - a generic type parameter, which we can call T for instance. We write the class assuming that we have a type T in mind, with the idea that we will fill in the type once we know what it is. This is how an ArrayList is implemented, for example. It is a dynamic array of some generic type T, and the exact type is decided (specialized) when we declare the ArrayList variable, for example ArrayList<String> a. If we write our entire class in terms of this unkown type parameter, we will be able to simply name the type later when we want to use it.

In this exercise, we will write the class TopResult. It will have a generic type parameter (you can call it T or something else). Type T must be a Comparable type (thus, the full generic type parameter would be <T extends Comparable<T>>).

A Comparable is an interface which is implemented by classes such as Integer, Double, Character, and String, which allow two members of the same type to be compared to one another to see which is larger. The interface has one method, compareTo, which returns a negative, zero, or positive result indicating whether the object is less than, equal to, or greater than the object it is being compared against:

> Integer three = 3, four = 4;
> three.compareTo(four)
-1
> four.compareTo(three)
1
> four.compareTo(four)
0

The TopResult task should implement the following public methods:

  • TopResult, a default constructor. Initially there should be no top result since no results have been seen yet.
  • newResult, which takes an object of type T, representing a new result, as a parameter, but does not return anything. This method will check whether the new result is better than the current top result, and if so, replace it, otherwise it will ignore it. If there is currently no top result (because no results had been seen yet), then the current result automatically becomes the top result.
  • getTopResult, which does not take any parameters but returns the current top result. If there is currently no top result (because no results have been seen yet), then this method should return null.
  • toString, which will return the toString value of the current top result, or a null if there have been no results yet.

The following shows an example use of this class:

> TopResult<Integer> tr = new TopResult<Integer>();
> tr.getTopResult() // no results seen yet, should be null
null
> tr.newResult(7);
> tr.getTopResult()
7
> tr.newResult(3);
> tr.getTopResult()
7
> tr.newResult(4);
> tr.getTopResult()
7
> tr.newResult(9);
> tr.getTopResult()
9
> tr.newResult(20);
> tr.getTopResult()
20
> tr.toString() // this will print the toString() of the current top result
"20"

Please make sure that it passes the following: https://repl.it/@micky123/SweetEmotionalExtraction

Please be sure that the work is your own, not a duplicate of somebody else's. Thank you.

Solutions

Expert Solution

// TopResult.java

public class TopResult<T extends Comparable<T>> {

      

       private T result;

      

       public TopResult()

       {

             result = null;

       }

      

       public void newResult(T new_result)

       {

            

             if(result == null || new_result.compareTo(result) > 0)

                    result = new_result;

       }

      

       public T getTopResult()

       {

             return result;

       }

      

       public String toString()

       {

             return result.toString();

       }

       public static void main(String[] args) {

            

             TopResult<Integer> tr = new TopResult<Integer>();

             System.out.println(tr.getTopResult()); // null

             tr.newResult(7);

             System.out.println(tr.getTopResult()); // 7

             tr.newResult(3);

             System.out.println(tr.getTopResult()); // 7

             tr.newResult(4);

             System.out.println(tr.getTopResult()); // 7

             tr.newResult(9);

             System.out.println(tr.getTopResult()); // 9

             tr.newResult(20);

             System.out.println(tr.getTopResult()); //20

             System.out.println(tr.toString()); // 20

            

       }

}

//end of TopResult.java

Output:


Related Solutions

Using Python 3, Write a class called GolfScore that keeps track of the score for a...
Using Python 3, Write a class called GolfScore that keeps track of the score for a person playing a round of golf. We will limit the round to 9 holes, just to make testing easier. As a reminder, the holes on the golf course are numbered 1 – 9. Create a class level variable named NUM_OF_HOLES set to 9. Methods to be written: The constructor – sets the score for all holes to -1 addScore (hole, score) – this method...
Write C++ a program that shows a class called gamma that keeps track of how many...
Write C++ a program that shows a class called gamma that keeps track of how many objects of itself there are. Each gamma object has its own identification called ID. The ID number is set equal to total of current gamma objects when an object is created. Test you class by using the main function below. int main()    {    gamma g1;    gamma::showtotal();    gamma g2, g3;    gamma::showtotal();    g1.showid();    g2.showid();    g3.showid();    cout <<...
Write a program in java that does the following: Create a StudentRecord class that keeps the...
Write a program in java that does the following: Create a StudentRecord class that keeps the following information for a student: first name (String), last name (String), and balance (integer). Provide proper constructor, setter and getter methods. Read the student information (one student per line) from the input file “csc272input.txt”. The information in the file is listed below. You can use it to generate the input file yourself, or use the original input file that is available alone with this...
(USE C ++ AND class STRING ONLY!!!! No java, No cstring and No vector) Write a...
(USE C ++ AND class STRING ONLY!!!! No java, No cstring and No vector) Write a program that can be used to train the user to use less sexist language by suggesting alternative versions of sentences given by the user. The program will ask for a sentence, read the sentence into a string variable, and replace all occurrences of masculine pronouns with genderneutral pronouns. For example, it will replace "he" with "she or he". Thus, the input sentence See an...
write a java program to evaluate the highest number input by user, cannot use math class,...
write a java program to evaluate the highest number input by user, cannot use math class, must use overloading . Must compute four computeHighNum methods. Here is what I have. import java.util.Scanner; public class Overload { public static void main(String[] args){ Scanner input = new Scanner(System.in); int number1 = input.nextInt(); int number2 = input.nextInt(); int number3 = input.nextInt();    //int maximum = maximum(number1, number2 ); System.out.printf("Highest integer is ");       // int number1 = input.nextInt(); // int number2 =...
Write a Java program that implements a song database. The SongsDatabase class keeps tracks of song...
Write a Java program that implements a song database. The SongsDatabase class keeps tracks of song titles by classifying them according to genre (e.g., Pop, Rock, etc.). The class uses a HashMap to map a genre with a set of songs that belong to such a genre. The set of songs will be represented using a HashSet. Your driver output should sufficiently prove that your code properly implements the code below. public class SongsDatabase { private Map<String, Set<String>> genreMap =...
The following class keeps track of how many flavors are at an ice-cream place, and the...
The following class keeps track of how many flavors are at an ice-cream place, and the number of calories of each flavor. The calories of each flavor ice-cream are positive values of type unsigned int and are stored as a dynamically allocated array. The first data member is a pointer that will point to the first element of the array. This array will be of an arbitrary size. The default size of the array shall be 25, but may be...
Write a C++ program for Euclids Algorithm that keeps track of the number of iterations (%...
Write a C++ program for Euclids Algorithm that keeps track of the number of iterations (% & loop) 1. Euclid’s Algorithm An alternative of the Euclidean algorithm for finding greatest common divisors (GCD) is repeatedly performing the modulo operation on two numbers until the remainder is 0. Here is the pseudocode for find the GCD of two positive numbers a and b using the Euclidean algorithm :while b ≠ 0 temp = b b = a mod t a =...
/////////////////JAVA PLEASE///////////////////////////////// Create a class called GVdate to keep track of a calendar date including month,...
/////////////////JAVA PLEASE///////////////////////////////// Create a class called GVdate to keep track of a calendar date including month, day and year.  You can do simple things like checking if it is your birthday, advancing to the next day, checking if a given date is valid and checking if it is a leap year. Class Fields/Instance Variables Provide appropriate names and data types for each of the private instance variables: the month, day and year (int) two final integers that represent YOUR birthday (month...
Python: Write a program that keeps track of a game score and declares the winner when...
Python: Write a program that keeps track of a game score and declares the winner when the game is over. A game is over when either one player scores 10 or more points with at least 2 more points than the opponent. A game is also over when one player scores 7 points and the opponent scores none. The program should begin by asking the names of the two players. Then, it should keep asking who won the point till...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT