Question

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 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.

This is my code:

public class Test {
public static void main(String[] args) throws IOException {
Stack<Character> stack = new Stack<>();
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\kenae\\Downloads\\palindrome.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\kenae\\Downloads\\palindrome.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();
}
}

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

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

public Stack() {
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() + "]";

}
}

My problem is that this code is not outputing the file I want it to output. It is in my downloads folder and the file name is palindrome.txt What am I doing wrong? It is running but there is nothing being outputed

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

Your program implementation is correct.

But in java File, IO could not work for the same file at a time for reading as well as writing.

So you have to change the files you could use something like this

BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\kenae\\Downloads\\palindrome.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\kenae\\Downloads\\palindrome_output.txt"));

It would work if you change the file names.

Please find the output below:

Add a comment
Know the answer?
Add Answer to:
I need help with this code This is what I need to do: Implement the Stack...
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
  • 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...

  • I was told I need three seperate files for these classes is there anyway to tie...

    I was told I need three seperate files for these classes is there anyway to tie all these programs together into one program after doing that. I'm using netbeans btw. import java.util.ArrayList; import java.util.Scanner; /** * * */ public class MySorts {       public static void main(String[] args) {             Scanner input = new Scanner(System.in);             String sentence;             String again;             do {                   System.out                               .println("Enter a sentence, I will tell you if it is a palindrome: ");...

  • 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...

  • 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...

  • Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

    Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix)    {        LinkedStack stack2 = new LinkedStack();        int val1;        int val2;        int result;        for(int i = 0; i < postFix.length(); i++)        {            char m = postFix.charAt(i);            if(Character.isDigit(m))            {                stack2.push(m);            }            else            {               ...

  • What is wrong with my code, when I pass in 4 It will not run, without...

    What is wrong with my code, when I pass in 4 It will not run, without the 4 it will run, but throw and error. I am getting the error   required: no arguments found: int reason: actual and formal argument lists differ in length where T is a type-variable: T extends Object declared in class LinkedDropOutStack public class Help { /** * Program entry point for drop-out stack testing. * @param args Argument list. */ public static void main(String[] args)...

  • I have added a little Code but I need help with the rest. /** A class...

    I have added a little Code but I need help with the rest. /** A class of stacks whose entries are stored in a chain of nodes. Implement all methods in MyStack class Main Reference : text book or class notes Do not change or add data fields */ package PJ2; public class MyStack<T> implements StackInterface<T> {    // Data fields    private Node<T> topNode; // references the first node in the chain    private int numberOfEntries;       public...

  • Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of...

    Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of the peek, isEmpty, size, and toString methods. See Base_A06Q1.java for a starting place and a description of these methods. Here is the base given: /** * Write a description of the program here. * * @author Lewis et al., (your name) * @version (program version) */ import java.util.Iterator; public class Base_A06Q1 { /** * Program entry point for stack testing. * @param args Argument...

  • how would I complete this code without calling any built-in java collection framework classes like ArrayList,...

    how would I complete this code without calling any built-in java collection framework classes like ArrayList, LinkedList, etc? import java.util.Iterator; class CallStack<T> implements Iterable<T> { // You'll want some instance variables here public CallStack() { //setup what you need } public void push(T item) { //push an item onto the stack //you may assume the item is not null //O(1) } public T pop() { //pop an item off the stack //if there are no items on the stack, return...

  • There is a data structure called a drop-out stack that behaves like a stack in every...

    There is a data structure called a drop-out stack that behaves like a stack in every respect except that if the stack size is n, then when the n+1element is pushed, the bottom element is lost. Implement a drop-out stack using links, by modifying the LinkedStack code. (size, n, is provided by the constructor. Request: Please create a separate driver class, in a different file, that tests on different types of entries and show result of the tests done on...

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