Question

Please help JAVA Create the following in Stack.java: An array of ints set to size 10...

Please help JAVA

  1. Create the following in Stack.java:

    1. An array of ints set to size 10 to represent the Stack, an int variable for the index

    2. A constructor that sets the index to -1

    3. A method called isEmpty (returns a boolean) that has no parameters. This method returns true if the Stack is empty and false if the Stack is not empty.

true

  1. A method called push(returns a Boolean) that takes an int as a parameter. This method pushes, or adds, the int to the stack if there is available space. Returns true if it got added successfully and false if wasn't able to be added to the stack

true

true

  1. A method called pop that takes has no parameter and returns an int. This method removes the next int from the stack and returns it.

Stack s = new Stack();

s.push(10);

s.push(20);

s.push(30);

System.out.println(s.pop());

System.out.println(s);

30

20, 10

  1. A method called peek that has no parameter. This method returns the next int from the Stack without removing, or popping, it from the Stack

Stack s = new Stack();

S.push(10);

s.push(20);

s.push(30);

System.out.println(s.peek());

System.out.println(s);

30

30, 20, 10

  1. Override the toString() method to be able to print the values in the stack separated by a comma. You should NOT pop() any of the values


30, 20, 10

  1. Create a class called LabStack

  1. Create the following in LabStack:

    1. A static method called popN that takes a stack st and an integer n as parameters. This method pops n items from st and returns an ArrayList that contains all the values that were popped.

Example (result in red)

[30, 20]

  1. A static method called popAll that takes a stack st as a parameter. This method pops all items from st and returns an ArrayList that contains all the values that were popped.

Example (output in red)

[30, 20, 10]

  1. A static method called reverse that takes an int array arr as a parameter. This method creates a local stack variable, puts all values from arr into the stack, then pops them to store them in a new int array. It returns the new int array, which should contain all the values from arr reversed.

[50, 40, 30, 20, 10]

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Stack.java

import java.util.ArrayList;

public class Stack {
private static final int MAX = 10;
private int index;
private int arr[] = new int[MAX];
  
public Stack()
{
this.index = -1;
}
  
public boolean isEmpty(){ return (this.index < 0); }
public boolean push(int num)
{
if(index >= (MAX - 1))
{
System.out.println("Stack Overflow!");
return false;
}
else
{
arr[++index] = num;
return true;
}
}
  
public int pop()
{
if(index < 0)
{
System.out.println("Stack Underflow!");
return 0;
}
else
{
int temp = peek();
arr[index] = -1; // assume, -1 signifies null
index--;
return temp;
}
}
  
public int peek()
{
if(index < 0)
{
System.out.println("Stack Underflow!");
return 0;
}
else
{
int temp = arr[index];
return temp;
}
}
  
public int getSize()
{
return (index + 1);
}
  
public int[] getStackArray(){ return this.arr; }
  
@Override
public String toString()
{
String out = "STACK: [";
if(index == -1)
{
out += "]\n";
return out;
}
  
ArrayList<Integer> list = new ArrayList<>();
for(int i = 0; i < arr.length; i++)
{
if(arr[i] > 0)
list.add(arr[i]);
}
  
for(int i = 0; i < list.size(); i++)
{
if(i == list.size() - 1)
out += list.get(i) + "]\n";
else
out += list.get(i) + ", ";
}
return out;
}
}

LabStack.java (Main class)

import java.util.ArrayList;
import java.util.Random;

public class LabStack {
  
public static void main(String[] args)
{
// create an instance of stack class
printMessage("Creating an instance of the Stack class..");
Stack stack = new Stack();
  
// generate 10 random numbers between 10 & 100 and push them to the stack
printMessage("\nGenerating 10 random numbers between 10 & 100 and pushing them to the Stack..");
Random rand = new Random();
for(int i = 0; i < 10; i++)
{
int pick = 10 + rand.nextInt(100);
while(pick < 10 || pick > 100)
pick = 10 + rand.nextInt(100);
stack.push(pick);
}
  
// display the initial contents of the stack
printMessage("\nInitial contents of the Stack..\n" + stack);
  
// now generate another random integer between 1 & (stack size / 2), for popping n values from the stack
int nVal = 1 + rand.nextInt(stack.getSize() / 2);
while(nVal < 1 || nVal > stack.getSize() / 2)
{
nVal = 1 + rand.nextInt(stack.getSize() / 2);
}
printMessage("\nPopping " + nVal + " integers from the stack..");
ArrayList<Integer> nValuesPopped = popN(stack, nVal);
printMessage(nValuesPopped + "");
printMessage("\nStack contents after popping " + nVal + " integers..\n" + stack);
  
// now reverse the stack containing the remaining integers
printMessage("Reversing the Stack contents..");
int[] arr = reverse(stack.getStackArray());
ArrayList<Integer> reversedList = new ArrayList<>();
for(int i = 0; i < arr.length; i++)
{
if(arr[i] > 0)
reversedList.add(arr[i]);
}
printMessage("STACK: " + reversedList);
  
// finally, we pop all the values from the stack
printMessage("\nPopping all the integers from the stack..");
ArrayList<Integer> nValuesPoppedAll = popAll(stack);
printMessage(nValuesPoppedAll + "");
printMessage("\nStack contents after popping all the integers..\n" + stack);
}
  
private static ArrayList<Integer> popN(Stack st, int n)
{
ArrayList<Integer> list = new ArrayList<>();
if(n > st.getSize())
{
System.out.println("n value exceeded stack size!");
return list;
}
  
for(int i = 0; i < n; i++)
{
list.add(st.pop());
}
return list;
}
  
private static ArrayList<Integer> popAll(Stack st)
{
ArrayList<Integer> list = new ArrayList<>();
while(!st.isEmpty())
{
int temp = st.pop();
if(temp > 0)
list.add(temp);
}
return list;
}
  
private static int[] reverse(int arr[])
{
Stack st = new Stack();
for(int i = 0; i < arr.length; i++)
st.push(arr[i]);
int reversedArray[] = new int[arr.length];
for(int i = 0; i < arr.length; i++)
{
int temp = st.pop();
if(temp >= 0)
reversedArray[i] = temp;
}
return reversedArray;
}
  
private static void printMessage(String msg)
{
System.out.println(msg);
}
}

************************************************************ SCREENSHOT ****************************************************

Add a comment
Know the answer?
Add Answer to:
Please help JAVA Create the following in Stack.java: An array of ints set to size 10...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JAVA 1.Write a static method named getMaxEven(numbers) which takes an array of positive integers as a...

    JAVA 1.Write a static method named getMaxEven(numbers) which takes an array of positive integers as a parameter. This method calculates and returns the largest even number in the list. If there are no even numbers in the array, the method should return 0. You can assume that the array is not empty. For example: Test Result int[] values = {1, 4, 5, 9}; System.out.println(getMaxEven(values)); 4 System.out.println(getMaxEven(new int[]{1, 3, 5, 9})); 0 public static int --------------------------------------------------------------------------------- 2. Write a static method...

  • JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array...

    JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array storing elements in the list • topOfStack: an int value representing the location of the stack top in the array • INITIAL_CAPACITY: the default capacity of the stack public class ArrayBasedStack <E> { private E[] data; private int topOfStack; private static final int INITIAL_CAPACITY = 5; } Add a constructor that will initialize the stack with a user-defined initial capacity. The top of the...

  • JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {    ...

    JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {     /**      * Searches through the ArrayList arr, from the first index to the last, returning an ArrayList      * containing all the indexes of Strings in arr that match String s. For this method, two Strings,      * p and q, match when p.equals(q) returns true or if both of the compared references are null.      *      * @param s The string...

  • JAVA HELP: Directions Write a program that will create an array of random numbers and output...

    JAVA HELP: Directions Write a program that will create an array of random numbers and output the values. Then output the values in the array backwards. Here is my code, I am having a problem with the second method. import java.util.Scanner; import java.util.Random; public class ArrayBackwards { public static void main(String[] args) { genrate(); print(); } public static void generate() { Scanner scanner = new Scanner(System.in);    System.out.println("Seed:"); int seed = scanner.nextInt();    System.out.println("Length"); int length = scanner.nextInt(); Random random...

  •    /**    * Returns an array of booleans that are set true or    *...

       /**    * Returns an array of booleans that are set true or    * false based on the associated values in the array    * arr using the following rules:    * 1. If arr[i] is divisible by three then the boolean    * value in the the array returned at the same position    * should be true    * 2. Unless the values in arr[i] is also divisible by 5,    * then the value returned...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • Create an ArrayListReview class with one generic type to do the following • Creates an array...

    Create an ArrayListReview class with one generic type to do the following • Creates an array list filled with the generic type of the ArrayListReview class, and inserts new elements into the specified location index-i in the list. (5 points) • Create a method inside the class to implement the calculation of Fibonacci numbers. Use System.nanoTime to find out how much time it takes to get fab(50). Create a method inside the class to check if an array list is...

  • Java - data structures Suppose that in the array-based stack, the array doubles in size after...

    Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...

  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • IN JAVA please Given a sorted array and a target value, return the index if the...

    IN JAVA please Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. Your code will be tested for runtime. Code which does not output a result in logarithmic time (making roughly log(2) N comparisons) will fail the tests. A sample main function is provided so that you may test your code on sample inputs. For testing purposes, the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT