Question

Implement the Stack Class with an ArrayList instead of an array, including the following functions: -empty...

Implement the Stack Class with an ArrayList instead of an array, including the following functions:

-empty
-push
-peek
-pop
-overrided toString() function which returns all of the stack's contents

Things to note:
-You no longer need a size.
-You no longer need to define a constant DEFAULT_CAPACITY. since ArrayLists grow dynamically.
-Whenever possible, use ArrayList functions instead of the [ ] (index operator) to implement your stack functions

Then write a driver program to do palindrome check. A string is said to be a palindrome if it does not change when the order of characters in the string is reversed. For example, MADAM, 45811854, and ABLE WAS I ERE I SAW ELBA are palindromes. In your driver program, you are required to use the Stack class that you create in this lab to do the string processing. Your program need to be able to read our provided text file, find which line is palindrome and which line is not, and output all of palindromes line by line to a new file. Submit your work for credit.

Hint: You may consider to use a string(initialized as empty) and your Stack class in your program that reads a line of sentence from the file, one character at a time, pushing only each letter character/number character(not special sign, etc.) onto a stack as it is read and simultaneously append it to the string. Then empty out the stack and put all of the letters/numbers to a second string, which is used to hold the reversed string. Next compare the first string and the second string to see if both are the same.

Please do this question in Java. I really don't understand how to incorporate the function within a file when reading it line by line and outputting it to another file.

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

Solution:

ListStack.java

import java.util.ArrayList;
import java.util.EmptyStackException;

public class ListStack<E> {
    private ArrayList<E> stack;

    public ListStack() {
        stack = new ArrayList<E>();
    }

    public void push(E item) {
        stack.add(item);
    }

    public E pop() {
        if (!isEmpty())
            return stack.remove(size()-1);
        else
            throw new EmptyStackException();
    }

    public boolean isEmpty() {
        return (stack.size() == 0);
    }

    public E peek() {
        if (!isEmpty())
            return stack.get(size()-1);
        else
            throw new EmptyStackException();
    }

    public int size() {
        return stack.size();
    }

    @Override
    public String toString() {
        return "ListStack [stack=" + stack.toString() + "]";

    }
}

Test.java

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException {
        ListStack<Character> stack = new ListStack<>();
        BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\input.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\output.txt"));
        String str;
        while((str = br.readLine()) != null){
            for(int i=0; i<str.length(); i++){
                stack.push(str.charAt(i));
            }
            String revofstr="";
            while (!stack.isEmpty()){
                revofstr += stack.pop().toString();
            }
            if(str.equals(revofstr)){
                bw.write("true");
                bw.newLine();
            }
            else{
                bw.write("false");
                bw.newLine();
            }
        }

        br.close();
        bw.close();
    }
}

input.txt

MADAM
45811854
ABLE WAS I ERE I SAW ELBA
MISI
GOIOG

output.txt

true
true
true
false
true

====================================================================================

====================================================================================

NOTE : you can print anything instead of true/false in output file. If you want to print palindrome string then you just need to change the if and else case into main() function as below

if(str.equals(revofstr)){
    bw.write(str+" is palindrome");
    bw.newLine();
}
else{
    bw.write(str+" is not palindrome");
    bw.newLine();
}

then your output.txt will be :

MADAM is palindrome
45811854 is palindrome
ABLE WAS I ERE I SAW ELBA is palindrome
MISI is not palindrome
GOIOG is palindrome
Add a comment
Know the answer?
Add Answer to:
Implement the Stack Class with an ArrayList instead of an array, including the following functions: -empty...
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
  • I need help with this code This is what I need to do: Implement the Stack...

    I need help with this code This is what I need to do: Implement the Stack Class with an ArrayList instead of an array, including the following functions: • empty • push • peek • pop • overrided toString( ) function which returns all of the stack’s contents Things to note: • You no longer need a size. • You no longer need to define a constant DEFAULT_CAPACITY. Since ArrayLists grow dynamically. • Whenever possible, use ArrayList functions instead of...

  • C++ Create an array-based implementation of a stack. Each element of the stack should store a...

    C++ Create an array-based implementation of a stack. Each element of the stack should store a string. The stack class should include 3 private member variables (maximum stack size, top of the stack index, and a pointer to the array that holds the stack elements). Public member methods should include a constructor (with an argument of stack maximum size that is used to create a dynamic array), a destructor (that deletes the dynamic array), a push method (argument is a...

  • USE C++ Create a Stack class that can handle characters. It should be able to automatically...

    USE C++ Create a Stack class that can handle characters. It should be able to automatically resize (to a larger size only) when full, becoming 1.5 times larger than it was. The stack class must contain the standard public functionality of push(), pop(), empty(). The only additional public functionality allowed isa peek() or top() method, depending upon your design choice. Do not use any of the STL (including the vector type) in your Stack. Test your Stack class by writing...

  • #19 with the following instructions 19. A palindrome is a string that can be read backward...

    #19 with the following instructions 19. A palindrome is a string that can be read backward and forward with the same result. For example, the following is a palindrome: Able was I ere I saw Elba. unction to test if a string is a palindrome using a stack. You can push characters in the stack one by one. When you reach the en string, you can pop the characters and form a new string. If the two strings are exactly...

  • Use Java to implement a basic stack using an array of integers. For the stack, you...

    Use Java to implement a basic stack using an array of integers. For the stack, you will create an array of integers that holds 5 numbers. To make it easier, you can declare the array at the class level. That way you will be able to use the array in any method in your class without using parameters. Your input/output interface should look something like the following: What operation do you want to do? push What number do you want...

  • Stack help. I need help with my lab assignment. Complete a method for a class named...

    Stack help. I need help with my lab assignment. Complete a method for a class named Palindrome that evaluates a string phrase to determine if the phrase is a palindrome or not. A palindrome is a sequence of characters that reads the same both forward and backward. When comparing the phrase to the same phrase with the characters in reverse order, an uppercase character is considered equivalent to the same character in lowercase, and spaces and punctuation are ignored. The...

  • 16.43 Lab 13C: Palindromes with Files and Functions Overview This is a demonstration of reading and...

    16.43 Lab 13C: Palindromes with Files and Functions Overview This is a demonstration of reading and writing files, along with using user-defined functions. Objectives Be able to read from an input file, perform string manipulation on each line of the file within a function, and write to an output file. Provided input file: A single input file named myinput.txt is provided that contains a few lines of text. bob sees over the moon never odd or even statistics dr awkward...

  • Write a program that uses a stack to reverse its inputs. Your stack must be generic...

    Write a program that uses a stack to reverse its inputs. Your stack must be generic and you must demonstrate that it accepts both String and Integer types. Your stack must implement the following methods: push, pop, isEmpty (returns true if the stack is empty and false otherwise), and size (returns an integer value for the number of items in the stack). You may use either an ArrayList or a LinkedList to implement your stack. Also, your pop method must...

  • in python and according to this #Creating class for stack class My_Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def Push(self, d): self.items.append(d) def Po...

    in python and according to this #Creating class for stack class My_Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def Push(self, d): self.items.append(d) def Pop(self): return self.items.pop() def Display(self): for i in reversed(self.items): print(i,end="") print() s = My_Stack() #taking input from user str = input('Enter your string for palindrome checking: ') n= len(str) #Pushing half of the string into stack for i in range(int(n/2)): s.Push(str[i]) print("S",end="") s.Display() s.Display() #for the next half checking the upcoming string...

  • C++: Learning Outcomes Implement two stacks and use them to implement an infix to prefix expression...

    C++: Learning Outcomes Implement two stacks and use them to implement an infix to prefix expression convertor Stacks A stack is an abstract data type which uses a sequential container and limits access to that container to one end. You may enter or remove from the container, but only at one end. Using the Linked List data structure from your last homework assignment, implement a Stack of type string. The Stack should only have one data member: the Linked List....

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