Question: Help me correct the function and my void keep function below : IMPORTANT DETAIL: Your implementation of LastN may not store more than nToKeep Strings.
Help me correct the function and my void keep function below :
IMPORTANT DETAIL: Your implementation of LastN may not store more than nToKeep Strings. You CANNOT store every Stringpassed to keep(). Points will be deducted if you use more memory than necessary. Assume that a LastN object may be asked to keep only the last 10 of a million strings.
public class LastN { int nToKeep=0; Stack
void keep(String s) { stack.push(s); }
String[] getLastN() { String[] str = new String[nToKeep]; for(int i=nToKeep - 1 ; i>=0 ;i--) { str[i] = stack.pop(); } return str; }
public static void main (String[] args) { LastN ln = new LastN(3); ln.keep("one"); ln.keep("two"); ln.keep("three"); ln.keep("four"); ln.keep("five"); String[] last = ln.getLastN(); for(int i=0;i My Input : one two The Output I got is : Exception in thread "main" java.util.NoSuchElementException: Stack underflow at Stack.pop(Stack.java:104) at LastN.getLastN(LastN.java:20) at TestLastN.zyBooksTest(TestLastN.java:75) at TestLastN.main(TestLastN.java:97) The correct out put should be : one two
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
