The first part of this lab is making your stackgeneric. Take the code from your working StringStack classand paste it into the GenericStack class. Change the name of theconstructors to match the new name of the class (this hasbeen done to this point), then modify the whole class soit uses generics, and can store any type that a programmer asksfor.
Until you successfully complete this, the main method will giveyou nasty compiler errors. Once they stop, you should be good tomove on!
Numbers and Readers
To take advantage of polymorphism, Java has a lot of inheritancehierarchies built-in. You may not have known that simple numericclasses, like Integer and Float, are actually part of one! Javacontains a generic number class creatively calledNumber, and pretty much any class in Java whosepurpose is to store numbers inherits from this class. (Note thatthis does not include the primitive int, float, and so on, sincethere are not classes)
Deep within Java's I/O packages, there's another interestinghierarchy of classes; the Reader and its manychildren. There are many types of Readers that can extractcharacters from different things, such as Strings, Files, andarrays. A function that takes in a Reader as a parameter, forexample,
Scrolls of Numbers
A few years back, I bought a box of random numbers from anintrepid salesman who insisted they were special. I'd like to findout if that's really the the case. Unfortunately, I've stored thenumbers in a bunch of different places - some of them are inStrings, others are in files, it's a bit of a mess.
So I created a generic calculator that, using Readers, can readin a list of numbers from any source, put them into a stack, andthen add them all up. Since I'm a good programmer, I put each ofthese steps in their own functions... but it looks like Iaccidentally erased some of them. Your next task in the lab is torepair my generic stack calculator by fixing thefunctions.
- makeStack is supposed to take in a Reader, of any kind, andreturn a stack of Numbers from the data in that Reader. Luckily,the only thing broken here is the function signature - fix it byspecifying the appropriate return type, function name, andparameters, using generics if appropriate.
- evaluate is supposed to take a stack of Numbers and add all ofthe numbers together, returning the result as a double. At somepoint, it looks like I replaced this entire function with a singlereturn 0.0. Whoops. You'll have to re-implement this function aswell as re-write its signature, again using generics ifappropriate.
A tip for this function: the Number class can't be directlyadded to a primitive (like a double, int, etc.) However, a Numberobject can be converted into a primitive with the use of thedoubleValue() function. You may need to use this! - I use the parse function to help with makeStack, but I musthave scuffed off the return type at some point. Find the rightreturn type by looking at the function and how it is used inmakeStack.
Wrapping up
You'll know when you've successfully completed this lab once youcan compile and run the code without errors, and you get outputthat looks somewhat like this (exact numbers may vary due tofloating point rounding):
76.476.399999618530274584425.015.324-------------------------------------------
package src;
import java.util.*;
public class GenericStack {
/* YOUR CODE HERE
  * Just like in the ArrayList lab, copy yourStringStack code, excluding the
  * main method, here.
  * Then, modify it so it's generic!
  */
private String[] stack;
public int size;
public int top;
/* Puts the stack into a valid state, ready for us to callmethods on.
* The size parameter tell the... well, size of the stack.
*/
public GenericStack(int size) {
this.top = -1;
this.size=size;
this.stack = new String[size];
}
/* If someone calls the constructor with no argument, theyshould get a
* stack with a default size of 10.
*/
public GenericStack() {
this.size=10;
this.stack = new String[this.size];
this.top = -1;
}
/* Return true if the stack has no elements, and falseotherwise.
*/
public boolean empty() {
return this.top == -1;
}
/* Return the object at the top of the stack, WITHOUT removingit.
* If there are no elements to peek, throw aNoSuchElementException.
*/
public String peek() {
if(this.top == -1) {
throw new NoSuchElementException(\"Empty stack!\");
}
return this.stack[this.top];
}
/* Return the object at the top of the stack, AND ALSO removeit.
* If there are no elements to pop, throw aNoSuchElementException.
*/
public String pop() {
if(this.top == -1) {
throw new NoSuchElementException(\"Empty stack!\");
}
return this.stack[this.top--];
}
/* Add a new object to the top of the stack.
* If there is no room in the stack, throw aIllegalStateException.
*/
public void push(String s) {
if(this.top == this.size-1) {
throw new IllegalStateException(\"Stack is full!\");
}
this.stack[++this.top] = s;
}
/* Return the position of an object on the stack. The positionof an object
* is just its distance from the top of the stack. So, thetopmost item is
* distance 0, the one below the topmost item is at distance 1,etc.
*/
public int search(String s) {
int distance = 0;
int top = this.top;
while (top >= 0) {
if(this.stack[top] == s) {
return distance;
}
distance++;
--top;
}
return -1;
}
public static void main(String[] args) {
// If any of these lines cause a compilation error, your stackhasn't
// been properly made generic.
GenericStack intStack = newGenericStack<>();
GenericStack stringStack = newGenericStack<>();
GenericStack> listStack = newGenericStack<>();
}
}
---------------------------
package src;
import java.util.*;
import java.io.*;
import java.math.*;
public class Calculator {
public static void main(String[] args) throwsFileNotFoundException, IOException {
String numbers = \"56 3 7 2.0 8.4\";
char[] moreNumbers = \"1.0 2 3 4 5 0.324\".toCharArray();
GenericStack stack1 = makeStack(newStringReader(numbers));
System.out.println(evaluate(stack1));
GenericStack stack2 = newGenericStack<>();
for (String token : numbers.split(\" \")) {
stack2.push(Float.parseFloat(token));
}
System.out.println(evaluate(stack2));
GenericStack stack3 = makeStack(newFileReader(\"numbers.txt\"));
System.out.println(evaluate(stack3));
GenericStack stack4 = makeStack(newCharArrayReader(moreNumbers));
System.out.println(evaluate(stack4));
}
 Â
/* This function is meant to take in a Reader called \"reader\" andreturn a
* stack of Numbers.
*
* Remember: don't change anything that's already there. Just addyour new
* code where the comment is to fix the function's signature.
*/
public static /* ??? */ throws IOException {
GenericStack stack = newGenericStack<>(64);
char[] data = new char[64];
reader.read(data);
String tokens = new String(data);
for (String token : tokens.split(\" \")) {
stack.push(parse(token));
}
return stack;
}
/* This function is meant to take in a stack of ANY KIND ofNumber
* called \"stack\", and return the double you get if you add all ofthe
* numbers together.
* The function must be able to accept a stack of ANY KIND ofNumber!
*
* Hint: use wildcard generics!
*/
public static /* ??? */ {
/* implement me! */
return 0.0;
}
/* This function is missing a return type.
* Examine it, and see if you can tell what type it shouldreturn.
* (Spoiler: it's probably what you think it is.)
*/
public static /* ??? */ parse(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) { }
try {
return Double.parseDouble(s);
} catch (NumberFormatException e) { }
return new BigDecimal(s);
}
}