Question

In: Computer Science

Complete the following for full credit in this assignment: Complete the coding requirement for the Class...

Complete the following for full credit in this assignment:

Complete the coding requirement for the Class Method Bodies:

Write the constructor: This should initialize all of your class fields and dynamically allocate memory for your array that will hold your stack data. You should use the constant “n” as the size for your fixed-size stack.

Write the push method: This should add the item in the formal parameter to your stack. Caveat: You need to check and make sure you aren’t going out of bounds with your array. If so, you need to ignore requests to add to the stack as it is full. After that, you can simply add the item and update your cursor (“top” field).

Write the toString method: If the stack is empty, simple return empty brackets “[]”. Otherwise, build a string that consists of every item in the stack inside the brackets and separated by commas (e.g. [1,2,3]). You must use a loop to do this, but you will likely have an extra comma at the end. You can use the substring method to remove the ending comma.

Write the isEmpty method: This can be done in one line if you are savvy. Simply return whether the size of your stack is zero or not.

Write the size method: This can also be done in one line depending on how you programmed the rest of the class. Simply return how many items are currently in the stack.

Write the peek method: This should return the value at the top of the stack. If the stack is empty, return -1. Caveat: Make sure you check whether the stack is empty BEFORE you try accessing array elements otherwise you could crash the program.

Write the pop method: This should return the value at the top of the stack and then remove that item from the stack. We can use “lazy evaluation” which means we don’t actually remove the item but only remove access to it. Simply decrement your cursor variable to remove access to it. If the stack is empty, return -1. Caveat: Make sure you check whether the stack is empty BEFORE you try accessing array elements otherwise you could crash the program.

Write a clear method. This should set the stack to the empty state. In other words, it “resets” the stack to how it was when you first created the stack object. You should use “Lazy Evaluation” for efficiency.

public class Lab05{
   public static void main(String[] args){
       StackInt st = new StackInt();
       p(st.isEmpty());           // This should be true
       p(st.peek());               // This should be -1
       p(st.size());               // This should be 0
       for(int i = 0; i < 10; i++)
           st.push(i);            // This adds 10 items to the stack
       p(st.toString());           // This should be [0,1,2,3,4,5,6,7,8,9]
       p(st.isEmpty());           // This should be false
       p(st.peek());               // This should be 9
       p(st.size());               // This should be 10
       p("Popped " + st.pop() + " from stack...");   // This should be "Popped 9 from stack..."
       p(st.toString());           // This should be [0,1,2,3,4,5,6,7,8]
       st.clear();                // This should clear the stack...
       p(st.isEmpty());           // This should be true
   }
  
   public static <E> void p(E s){
       System.out.println(s);
   }
}

Solutions

Expert Solution

GIVE THUMPS UP

here's, your java code for the above question.

I HAVE COMMENTED DOWN THE WORK OF EACH OF THE STACK'S METHOD. I HAVE DONE THIS CODE IN NOTEPAD++ EDITOR AND RUN THROUGH CMD.

SOURCE CODE:

/* JAVA CODE */

import java.util.*;

class Stack{
   int stack[];
   int top;
   int max;
  
   //constructor for initializing stack
   Stack(int maxSize){
       stack = new int[maxSize];
       max = maxSize;
       top = -1;
   }
  
   //this fuction is used to add an elelments in stack
   public void push(int data){
       if(top == (max - 1)){
           System.out.println("STACK OVERFLOW!!!");
           System.exit(1);
       }
       stack[++top] = data;
   }
  
   //Thsi fuction is used to check, stack is empty or not.
   public boolean isEmpty(){
       if(top == -1){
           return true;
       }
       return false;
   }
  
   //toString fuvtion is used to print stack
   public String toString(){
       String result = "";
       if(isEmpty()){
           return "[]";
       }
       else{
           for(int i=top;i>=1;i--){
               result = "," + stack[i] + result;
           }
           result = "[" + stack[0] + result + "]";
       }
       return result;
      
   }
  
   //Returning size of the stack
   public int size(){
       return top+1;
   }
  
   //returning peek/top element of the stack
   public int peek(){
       if(isEmpty()){
           return -1;
       }
       return stack[top];
   }
  
   //returning pop elelment of the stack.
   public int pop(){
       if(isEmpty()){
           System.out.println("STACK UNDERFLOW");
           System.exit(1);
       }
       return stack[top--];
   }
  
   //this method is used to reset the stack or clear all the stack
   public void clear(){
       top = -1;
   }
  
   public static void main(String[] args){
       Stack st = new Stack(20);
       System.out.println(st.isEmpty()); //this should be true
       System.out.println(st.peek()); //this should be -1
       System.out.println(st.size()); //this should be 0
       for(int i=0;i<10;i++){
           st.push(i); //this adds 10 items to the stack.
       }
       System.out.println(st.toString()); //this should be [0,1,2,3,4,5,6,7,8,9]
       System.out.println(st.isEmpty()); //this should be false
       System.out.println(st.peek()); //this should be 9
       System.out.println(st.size()); //this should be 10
       System.out.println("Popped " + st.pop() + " from Stack..."); //this should be " Popped from 9 from the stack..."
       System.out.println(st.toString()); //this should be[0,1,2,3,4,5,6,7,8]
       st.clear(); //this should be clear the stack
       System.out.println(st.isEmpty()); //this should be true.
      
   }
  
}

OUTPUT :

true
-1
0
[0,1,2,3,4,5,6,7,8,9]
false
9
10
Popped 9 from Stack...
[0,1,2,3,4,5,6,7,8]
true

SCREENSHOT :

IF YOU HAVE ANY DOUBTS, DO COMMENT IN COMMENT BOX. GIVE THUMPS UP...


Related Solutions

Complete the following table and compute the project’s conventional payback period.(Note: For full credit, complete the...
Complete the following table and compute the project’s conventional payback period.(Note: For full credit, complete the entire table. Round the conventional payback period to the nearest two decimal places. If your answer is negative use a minus sign.) Year 0 Year 1 Year 2 Year 3 Expected cash flow -$5,000,000 $2,000,000 $4,250,000 $1,750,000 Cumulative cash flow Conventional payback period: years The conventional payback period ignores the time value of money, and this concerns Green Caterpillar’s CFO. He has now asked...
Coding Java Assignment Write the following static methods. Assume they are all in the same class....
Coding Java Assignment Write the following static methods. Assume they are all in the same class. Assume the reference variable input for the Scanner class and any class-level variables mentioned are already declared. All other variables will have to be declared as local unless they are parameter variables. Use printf. A method that prompts for the customer’s name and returns it from the keyboard. A method called shippingInvoice() that prompts for an invoice number and stores it in a class...
Height Requirement Assignment Use the given parameters to complete the assignment: Men's heights are normally distributed...
Height Requirement Assignment Use the given parameters to complete the assignment: Men's heights are normally distributed with mean 69.5 in. and standard deviation 2.4 inches. Women's heights are normally distributed with mean 63.8 in. and standard deviation 2.6 inches. The U.S. Air Force requires pilots to have heights between 64 in. and 77 in. Answer the following questions for the height requirement for U.S. Air Force pilots. a) What percent of women meet the height requirements? b) What percent of...
Innocence Project Written Assignment Provide answers to the following questions. Remember, to receive full credit you...
Innocence Project Written Assignment Provide answers to the following questions. Remember, to receive full credit you must answer each of the QUESTIONS OF THE CASE THAT FOLLOWS , along with the summary questions. Case Name (1/2 Page): ___________________ 1-In ONE complete sentence describe the crime that occurred in your own words, informed by the Innocence Project website or as found in your web-based research. 2-What is the status of the case? Has the person convicted of the crime been exonerated...
Innocence Project Written Assignment Provide answers to the following questions. Remember, to receive full credit you...
Innocence Project Written Assignment Provide answers to the following questions. Remember, to receive full credit you must answer each of the QUESTIONS OF THE CASE THAT FOLLOWS , along with the summary questions. Case Name (1/2 Page): ___________________ 1-In ONE complete sentence describe the crime that occurred in your own words, informed by the Innocence Project website or as found in your web-based research. 2-What is the status of the case? Has the person convicted of the crime been exonerated...
The time taken to complete an assignment in a class follows a normal distribution with a...
The time taken to complete an assignment in a class follows a normal distribution with a mean of105 minutes and a standard deviation of 10 minutes. A. What is the probability that a randomly selected student takes between 100and 112 minutes to complete the exam? B. What is the probability that a randomly selected student takes less than 115minutes to complete the exam? C. What is the time that corresponds to the 38th percentile? D. Between which two values does...
coding the following project: Setting up structures to store and retrieve data. A major requirement of...
coding the following project: Setting up structures to store and retrieve data. A major requirement of virtually all projects in the financial world involves the storage and retrieval of data. project must be properly modularized and allow for more than one way to store the data to satisfy the various needs of clients.The first manner is by storing data using hashtables (or hash maps) as the basis of storing and retrieving data.
Complete the coding/testing of the heap sort method we began in class. Then modify your program...
Complete the coding/testing of the heap sort method we began in class. Then modify your program so that it outputs a comparison of the actual number of swaps it performs to the predicted number of swaps, and a comparison of the actual sort effort to the predicted and minimum sort effort. The output should be formatted exactly as shown below. Actual swaps = xxxx; Predicted swaps = xxxx Actual sort effort = xxxx; Predicted sort effort = xxxx; Min sort...
ACCY 1 Accounting Fundamentals Extra Credit Assignment – Journal Entry Practice Complete the following requirements by...
ACCY 1 Accounting Fundamentals Extra Credit Assignment – Journal Entry Practice Complete the following requirements by hand and upload your work in pdf to Canvas by March 20. No late assignment will be accepted. CASE: World Co. commenced operations on January 1, 2018 and has a year end of December 31 (reporting date). The company uses a perpetual inventory method. During 2018, the company had the following events: 1. January 1. Issued common stock for $40,000 cash. 2. April 1...
For their economic class, students are asked to form pairs to complete an assignment. The professor...
For their economic class, students are asked to form pairs to complete an assignment. The professor asks them to work together but to turn only one copy of the problem set. Johnny and Kristen, two students of the class, decide to work together. Both of the students value the assignment. However, because Kristen and Johnny received different grades at the exam, they do not value the assignment the same way: Kristen would receive a payoff of 10 if the assignment...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT