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

Note: Done accordingly. Please comment for any problem. Please Uprate. 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) {
       a = (T[]) new Object[capacity];
       N = 0;
   }
  

   public boolean isEmpty() {
       return N == 0;
   }

   public boolean isFull() {
       return N == a.length;
   }

   public void push(T item) {
       a[N++] = item;
   }

   public T pop() {
       return a[--N];
   }

   public T peek() {
       return a[N - 1];
   }

   public Iterator<T> iterator() {
       return new ReverseArrayIterator();
   }

   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.Arrays;
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 given capacity
   public RArrayStack() {
       a = (T[]) new Object[8];
       N = 0;
   }
  
   public void resize(int capacity){
       T[] largerArray = Arrays.copyOf(a, 2*capacity);
       a=largerArray;
      
   }
  

   public boolean isEmpty() {
       return N == 0;
   }

   public boolean isFull() {
       return N == a.length;
   }

   public void push(T item) {
       if(isFull()){
           resize(a.length);
           //System.out.println("New length"+a.length);
       }
       a[N++] = item;
   }

   public T pop() {
       return a[--N];
   }

   public T peek() {
       return a[N - 1];
   }

   public Iterator<T> iterator() {
       return new ReverseArrayIterator();
   }

   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();
       }
   }
}

Main.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {

   public static void arrayStack(){
       BufferedReader reader;
       try {
           ArrayStack<Integer> number=new ArrayStack<Integer>(30);
           ArrayStack<String> text=new ArrayStack<String>(30);
           reader = new BufferedReader(new FileReader(
                   "Numbers.txt"));
           String line = reader.readLine();
           while (line != null) {
               // read next line
               number.push(Integer.parseInt(line));
               line = reader.readLine();
           }
           reader.close();

           for(Object item : number){
               System.out.println(item.toString());
           }
          
          
           reader = new BufferedReader(new FileReader(
                   "tinyTale.txt"));
           line = reader.readLine();
           while (line != null) {
               // read next line
               text.push(line);
               line = reader.readLine();
           }
           reader.close();

           for(Object item : text){
               System.out.println(item.toString());
           }
          
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
  
   public static void rArrayStack(){
       BufferedReader reader;
       try {
           RArrayStack<Integer> number=new RArrayStack<Integer>();
           RArrayStack<String> text=new RArrayStack<String>();
           reader = new BufferedReader(new FileReader(
                   "Numbers.txt"));
           String line = reader.readLine();
           while (line != null) {
               // read next line
               number.push(Integer.parseInt(line));
               line = reader.readLine();
           }
           reader.close();

           for(Object item : number){
               System.out.println(item.toString());
           }
          
          
           reader = new BufferedReader(new FileReader(
                   "tinyTale.txt"));
           line = reader.readLine();
           while (line != null) {
               // read next line
               text.push(line);
               line = reader.readLine();
           }
           reader.close();

           for(Object item : text){
               System.out.println(item.toString());
           }
          
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
  
   public static void main(String[] args) {
       System.out.println("Array Stack :");
       arrayStack();
       System.out.println("RArray Stack :");
       rArrayStack();
   }

}

Output:


Related Solutions

(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...
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...
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++ 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...
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:...
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...
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...
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...
Create a class called RandomWhen. The program must continuously generate a random number between 1 and...
Create a class called RandomWhen. The program must continuously generate a random number between 1 and 100 inclusive. The program must stop when the number 1 is generated, and the loop iteration will be printed. Run the program 3 different times. Sample output: It took ## iterations to generate a 1. It took ## iterations to generate a 1. It took # iterations to generate a 1.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT