Question

In: Computer Science

1. create a class called ArrayStack that is a generic class. Create a main program to...

1. create a class called ArrayStack that is a generic class. Create a main program to read in one input file and print out the file in reverse order by pushing each item on the stack and popping each item off to print it. The two input files are: tinyTale.txt and numbers.txt. Rules: You cannot inherit the StackofStrings class.

2. Using your new ArrayStack, create a new class called RArrayStack. To do this, you need

a) remove the capacity parameter from the constructor and create the array with 8 as the starting size

b) create a new method called resize that takes a parameter (capacity)

c) change push() to check for length of array. If it is at the limit then call resize to increase it to twice the size Use the same main program from 1 and the two input files to test out your program. RULE: You cannot use ArrayList – you must use a primitive Java arrays.

  

import java.util.Iterator;
import java.util.NoSuchElementException;

public class StackOfStrings implements Iterable<String> {
private String[] a; // holds the items
private int N; // number of items in stack

// create an empty stack with given capacity
public StackOfStrings(int capacity) {
a = new String[capacity];
N = 0;
}

public boolean isEmpty() {
return N == 0;
}
  
public boolean isFull() {
return N == a.length;   
}
  
public void push(String item) {
a[N++] = item;
}
  
public String pop() {
return a[--N];
}
  
public String peek() {
return a[N-1];
}
  
public Iterator<String> iterator() {
return new ReverseArrayIterator();
}

public class ReverseArrayIterator implements Iterator<String> {
private int i = N-1;

public boolean hasNext() {
return i >= 0;
}

public String next() {
if (!hasNext()) throw new NoSuchElementException();
return a[i--];
}

public void remove() {
throw new UnsupportedOperationException();
}
}
}

Numbers.txt

20
7
99
88
1
2
3
4
30
16
19
50
55
60
61
6
68
28
32
--------------------------------------------------------------

tinyTale.txt

it was the best of times it was the worst of times
it was the age of wisdom it was the age of foolishness
it was the epoch of belief it was the epoch of incredulity
it was the season of light it was the season of darkness
it was the spring of hope it was the winter of despair

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

//ArrayStack.java

import java.util.Iterator;

import java.util.NoSuchElementException;

public class ArrayStack<T> implements Iterable<T> {

      private T[] a; // holds the items

      private int N; // number of items in stack

      // create an empty stack with given capacity

      public ArrayStack(int capacity) {

            // initializing an array of T type objects

            a = (T[]) new Object[capacity];

            N = 0;

      }

      // returns true if stack is empty

      public boolean isEmpty() {

            return N == 0;

      }

      // returns true if stack is full

      public boolean isFull() {

            return N == a.length;

      }

      // adds an element to top, assuming stack is not full

      public void push(T item) {

            a[N++] = item;

      }

      // removes and returns an element from top, assuming stack is not empty

      public T pop() {

            return a[--N];

      }

     

      //returns top element without removing

      public T peek() {

            return a[N - 1];

      }

     

      //returns an iterator

      public Iterator<T> iterator() {

            return new ReverseArrayIterator();

      }

     

      //private Iterator class

      public class ReverseArrayIterator implements Iterator<T> {

            private int i = N - 1;

            public boolean hasNext() {

                  return i >= 0;

            }

            public T next() {

                  if (!hasNext())

                        throw new NoSuchElementException();

                  return a[i--];

            }

            public void remove() {

                  throw new UnsupportedOperationException();

            }

      }

}

//RArrayStack.java

import java.util.Iterator;

import java.util.NoSuchElementException;

public class RArrayStack<T> implements Iterable<T> {

      private T[] a; // holds the items

      private int N; // number of items in stack

      // create an empty stack with default capacity

      public RArrayStack() {

            // initializing an array with initial capacity as 8

            a = (T[]) new Object[8];

            N = 0;

      }

      // returns true if stack is empty

      public boolean isEmpty() {

            return N == 0;

      }

      // this stack is never full, since the array is resizable, so i'm just

      // commenting this method out.

      // public boolean isFull() {

      // return N == a.length;

      // }

      // adds an element to top

      public void push(T item) {

            // resizing array to double capacity if full

            if (N == a.length) {

                  resize(N * 2);

            }

            a[N++] = item;

      }

      // removes and returns an element from top, assuming stack is not empty

      public T pop() {

            return a[--N];

      }

      // returns top element without removing

      public T peek() {

            return a[N - 1];

      }

      // returns an iterator

      public Iterator<T> iterator() {

            return new ReverseArrayIterator();

      }

      // method to resize the array when full

      private void resize(int newCapacity) {

            // creating new array

            T[] newArr = (T[]) new Object[newCapacity];

            // copying all elements

            for (int i = 0; i < N && i < newCapacity; i++) {

                  newArr[i] = a[i];

            }

            // replacing old with new array

            a = newArr;

      }

      // private Iterator class

      public class ReverseArrayIterator implements Iterator<T> {

            private int i = N - 1;

            public boolean hasNext() {

                  return i >= 0;

            }

            public T next() {

                  if (!hasNext())

                        throw new NoSuchElementException();

                  return a[i--];

            }

            public void remove() {

                  throw new UnsupportedOperationException();

            }

      }

}

//Main1.java demonstrating ArrayStack

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class Main1 {

      public static void main(String[] args) throws FileNotFoundException {

            // opening tinyTale.txt, make sure you have the file in same directory

            Scanner scanner = new Scanner(new File("tinyTale.txt"));

            // creating a String ArrayStack of capacity 1000

            ArrayStack<String> stringStack = new ArrayStack<String>(1000);

            // looping through the file, adding each LINE to the stack (not word)

            // if you want to add single word, then change scanner.nextLine() to

            // scanner.next()

            while (scanner.hasNext()) {

                  stringStack.push(scanner.nextLine());

            }

            System.out.println("tinyTale.txt in reverse order (lines)");

            // displaying the file in reverse order

            while (!stringStack.isEmpty()) {

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

            }

            scanner.close();

            // opening numbers.txt file, make sure it exists in the current working

            // directory too

            scanner = new Scanner(new File("numbers.txt"));

            // creating a Integer ArrayStack of capacity 1000

            ArrayStack<Integer> intStack = new ArrayStack<Integer>(1000);

            // looping through the file, adding each number to the stack

            while (scanner.hasNext()) {

                  intStack.push(Integer.parseInt(scanner.nextLine()));

            }

            System.out.println("\nnumbers.txt in reverse order");

            // displaying the file in reverse order

            while (!intStack.isEmpty()) {

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

            }

            scanner.close();

      }

}

//Main2.java demonstrating RArrayStack

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class Main2 {

      public static void main(String[] args) throws FileNotFoundException {

            // opening tinyTale.txt, make sure you have the file in same directory

            Scanner scanner = new Scanner(new File("tinyTale.txt"));

            // creating a String RArrayStack

            RArrayStack<String> stringStack = new RArrayStack<String>();

            // looping through the file, adding each LINE to the stack (not word)

            // if you want to add single word, then change scanner.nextLine() to

            // scanner.next()

            while (scanner.hasNext()) {

                  stringStack.push(scanner.nextLine());

            }

            System.out.println("tinyTale.txt in reverse order (lines)");

            // displaying the file in reverse order

            while (!stringStack.isEmpty()) {

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

            }

            scanner.close();

            // opening numbers.txt file, make sure it exists in the current working

            // directory too

            scanner = new Scanner(new File("numbers.txt"));

            // creating a Integer RArrayStack

            RArrayStack<Integer> intStack = new RArrayStack<Integer>();

            // looping through the file, adding each number to the stack

            while (scanner.hasNext()) {

                  intStack.push(Integer.parseInt(scanner.nextLine()));

            }

            System.out.println("\nnumbers.txt in reverse order");

            // displaying the file in reverse order

            while (!intStack.isEmpty()) {

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

            }

            scanner.close();

      }

}

//OUTPUT

tinyTale.txt in reverse order (lines)

it was the spring of hope it was the winter of despair

it was the season of light it was the season of darkness

it was the epoch of belief it was the epoch of incredulity

it was the age of wisdom it was the age of foolishness

it was the best of times it was the worst of times

numbers.txt in reverse order

32

28

68

6

61

60

55

50

19

16

30

4

3

2

1

88

99

7

20


Related Solutions

1. create a class called ArrayStack that is a generic class. Create a main program to...
1. create a class called ArrayStack that is a generic class. Create a main program to read in one input file and print out the file in reverse order by pushing each item on the stack and popping each item off to print it. The two input files are: tinyTale.txt and numbers.txt. Rules: You cannot inherit the StackofStrings class. 2. Using your new ArrayStack, create a new class called RArrayStack. To do this, you need a) remove the capacity parameter...
(In C++) Bank Account Program Create an Account Class Create a Menu Class Create a main()...
(In C++) Bank Account Program Create an Account Class Create a Menu Class Create a main() function to coordinate the execution of the program. We will need methods: Method for Depositing values into the account. What type of method will it be? Method for Withdrawing values from the account. What type of method will it be? Method to output the balance of the account. What type of method will it be? Method that will output all deposits made to the...
C++, ArrayStack. Make a main using the following arraystack structure the main most do the following...
C++, ArrayStack. Make a main using the following arraystack structure the main most do the following Stack: Stack 1 and Stack 2 most have their own result stack1.push(1) stack1.push(2) stack2.push(3) stack2.push(4) stack1.pop() stackTop = stack2.peek() stack1.push(stackTop) stack1.push(5) stack2.pop() stack2.push(6) ArrayStackInterface.h // Created by Frank M. Carrano and Tim Henry. // Copyright (c) 2013 __Pearson Education__. All rights reserved. /** @file StackInterface.h */ #ifndef _STACK_INTERFACE #define _STACK_INTERFACE template<class ItemType> class StackInterface { public: /** Sees whether this stack is empty. @return...
Create a new class called Account with a main method that contains the following: • A...
Create a new class called Account with a main method that contains the following: • A static variable called numAccounts, initialized to 0. • A constructor method that will add 1 to the numAccounts variable each time a new Account object is created. • A static method called getNumAccounts(). It should return numAccounts. Test the functionality in the main method of Account by creating a few Account objects, then print out the number of accounts
C++, ArrayStack, data structure. Make a main using the following arraystack structure the main most do...
C++, ArrayStack, data structure. Make a main using the following arraystack structure the main most do the following Stack: Stack 1 and Stack 2 most have their own result I need to see the state of the stack1 and stack2 after doing the following operation. (stack1 and stack2 need to have individually there own state result) stack1.push(1) stack1.push(2) stack2.push(3) stack2.push(4) stack1.pop() stackTop = stack2.peek() stack1.push(stackTop) stack1.push(5) stack2.pop() stack2.push(6) ArrayStackInterface.h // Created by Frank M. Carrano and Tim Henry. // Copyright...
Instructions Using the installed software for this course create a generic class called VehicleRental which accepts...
Instructions Using the installed software for this course create a generic class called VehicleRental which accepts any generic type of Vehicle ( create an instance of Car, Van and MotorCycle classes) Each type of Vehicle object has methods called drive, start and stop ( add simple print statement) The VehicleRental class has a method called rent which accept a generic type of Vehicle object, this method will call drive method of passed Vehicle object The solution will produce the following:...
C++ program homework question 1 1. Create and implement a class called clockType with the following...
C++ program homework question 1 1. Create and implement a class called clockType with the following data and methods (60 Points.): Data: Hours, minutes, seconds Methods: Set and get hours Set and get minutes Set and get seconds printTime(…) to display time in the form of hh:mm:ss default and overloading constructor Overloading Operators: << (extraction) operator to display time in the form of hh:mm:ss >> (insertion) operator to get input for hours, minutes, and seconds operator+=(int x) (increment operator) to...
Create a project called rise. Add a class called GCD. Complete a program that reads in...
Create a project called rise. Add a class called GCD. Complete a program that reads in a numerator (as an int) and a denominator (again, as an int), computes and outputs the GCD, and then outputs the fraction in lowest terms. Write your program so that your output looks as close to the following sample output as possible. In this sample, the user entered 42 and 56, shown in green. Enter the numerator: 42 Enter the denominator: 56 The GCD...
Generic types A class or interface that declares one or more generic variables is called a...
Generic types A class or interface that declares one or more generic variables is called a generic type. In this portion of the activity, you will make a class generic. Open GenericsC.java in jGRASP then compile it. At this point you should be familiar with the two type-safety warnings given by the compiler. You should be able to understand the source of the error: the use of the raw types List and Collection. Since the List being declared (al) is...
Java Programming Create a class named Problem1, and create a main method, the program does the...
Java Programming Create a class named Problem1, and create a main method, the program does the following: - Prompt the user to enter a String named str. - Prompt the user to enter a character named ch. - The program finds the index of the first occurrence of the character ch in str and print it in the format shown below. - If the character ch is found in more than one index in the String str, the program prints...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT