Question

(JAVA) Why is my toString method not printing out the last node? It will not print...

(JAVA) Why is my toString method not printing out the last node? It will not print out "A" which is for Alice. Everything else is working just fine except for this.

package driver;

import exception.StackException;

import stack.*;

public class StackDriver

{

public static void main(String[] args) throws Exception

{

StackInterface<Painting> painting = new LinkedStack <Painting>();

try

{

System.out.println("Peeking at top of player stack.\n" + painting.peek());

}catch (StackException e)

{

System.out.println(e);

System.out.println("Let's double check if it's empty: " + painting.isEmpty());

}

System.out.print("Printing out the size of the stack: " + painting.size());

System.out.println("\nCreating five paintings.");

Painting A = new Painting("Alice", "random" , "romance");

Painting B = new Painting("Byran", "random" , "romance");

Painting C = new Painting("Cathy", "random" , "romance");

Painting D = new Painting("Daniel", "random" , "romance");

Painting E = new Painting("Emily", "random" , "romance");

painting.push(A);

painting.push(B);

painting.push(C);

painting.push(D);

painting.push(E);

System.out.println("Testing the size method:\n" + painting.size());

System.out.println("Testing the peek method:\n" + painting.peek());

System.out.println("Testing the pop method:\n" + painting.pop());

System.out.println("Testing the peek method again to check if pop method workerd:\n"

+ painting.peek());

System.out.println("Testing the size method again:\n" + painting.size());

System.out.println("Testing the isEmpty method again:\n" + painting.isEmpty());

System.out.println("\nTesting stack method peek with Painting class methods:\n" +

painting.peek());

System.out.println("Peek at artist: " + painting.peek().getArtist());

System.out.println("Peek at genre: " + painting.peek().getGenre());

System.out.println("Peek at era: " + painting.peek().getEra());

System.out.println("Printing out the stack:\n" + painting);

System.out.println("Printing out the stack:\n" + painting);

}

}

package stack;

import exception.StackException;

/**

* Represents a linked implementation of a stack.

*

* @author Katareyna Guerra

*/

public class LinkedStack<T> implements StackInterface<T>

{

private int count;

private LinearNode<T> top;

/**

   * Creates an empty stack.

   */

public LinkedStack()

{

count = 0;

top = null;

}

//creates the node

public LinkedStack(T element) {

count = 1;

LinearNode<T> node = new LinearNode<T>(element);

top = node;

}

/**

   * Adds the specified element to the top of this stack.

   * @param element element to be pushed on stack

   */

public void push(T element)

{

LinearNode<T> node = new LinearNode<T>(element);

if(count != 0)

node.setNext(top);

top = node;

count++;

}

/**

   * Removes the element at the top of this stack and returns a

   * reference to it.

   * @return element from top of stack

   * @throws StackException if the stack is empty

   */

public T pop() throws StackException

{

if (isEmpty())

throw new StackException();

T temp = top.getElement();

top = top.getNext();

count--;

return temp;

}

/**

   * Returns a reference to the element at the top of this stack.

   * The element is not removed from the stack.

   * @return element on top of stack

   * @throws StackException if the stack is empty

   */

public T peek() throws StackException

{

if(isEmpty())

throw new StackException();

  

return top.getElement();

}

/**

   * Returns true if this stack is empty and false otherwise.

   * @return true if stack is empty

   */

public boolean isEmpty()

{

return count == 0;

}

  

/**

   * Returns the number of elements in this stack.

   * @return number of elements in the stack

   */

public int size()

{

return count;

}

/**

   * Returns a string representation of this stack.

   * @return string representation of the stack

   */

public String toString()

{

String result = "";

LinearNode<T> temp = top;

  

while(temp.getNext() != null){

result += temp.getElement();

  

temp = temp.getNext();

}

return result;

}

}

Homework Answers

Answer #1

Ans:

Please rectify the condition inside the while loop of the toString() method.

Below is the updated code for the same:

public String toString(){
    String result = "";
    LinearNode<T> temp = top;
    while(temp != null){
        result += temp.getElement();
        temp = temp.getNext();
    }
    return result;
}

// After the above correction your code will be printing the last node as well.

// If you have any query do ask in the comments section.

// If you found the answer helpful do give a Thumbs Up!!

Know the answer?
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
Similar Questions
class Car{ private String make; public Car(String make){ this.make = make; } public String toString(){ return...
class Car{ private String make; public Car(String make){ this.make = make; } public String toString(){ return make; } } class Node<T>{ public T data; public Node next; public Node(T data){ this.data = data; this.next = null; } } public class StackLinkedList<T>{ //Single field of type Node    //to represent the front of the stack //operation push() /* The push operation is equivalent to the inserting a node at the head of the list. */ public void push(T data){ } //operation...
Consider a generic Stack class implemented using linked list with the following methods: public boolean isEmpty(),...
Consider a generic Stack class implemented using linked list with the following methods: public boolean isEmpty(), which returns true if and only if the stack is empty; public T pop() throws StackUnderflowException, which removes and returns the top element of the stack (if the stack is empty, it throws StackUnderflowException); public T peek() throws StackUnderflowException, which returns the top element of the stack (but does not remove it; it throws exception if stack is empty); public void push(T element), which...
What does the following function do? public T doSomething() throws EmptyCollectionException{       if (isEmpty())             throw new EmptyCollectionException(“St
What does the following function do? public T doSomething() throws EmptyCollectionException{       if (isEmpty())             throw new EmptyCollectionException(“Stack”);       T result = top.getElement();        top = top.getNext();        count--;        return result; } Select one: a. isEmpty() b. Push() c. Pop() d. Peek()
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped...
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped everytime instead of the one. If there is only one element in the stack, just pop the one element and report that the stack is now empty. If stack is empty, it should just report that stack is empty. All other functions for StackArray remain the same. using java StackArray.java: public class StackArray {       private final int size = 20; //Size of...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {    public static final int DEFAULT_SIZE = 10;    private Object data[];    private int index; code 2 package test; import java.util.*; /* Class Node */ class Node { protected Object data; protected Node link; /* Constructor */ public Node() { link = null; data = 0; } /* Constructor */ public Node(Object d,Node n) { data = d; link = n; } /*...
ex3 Write a method public static boolean isPalindrome(String input) that uses one or more stacks to...
ex3 Write a method public static boolean isPalindrome(String input) that uses one or more stacks to determine if a given string is a palindrome. [A palindrome is a string that reads the same forwards and backwards, for example ‘racecar’, ‘civic’]. Make sure that your method works correctly for special cases, if any. What is the big-O complexity of your method in terms of the list size n. Supplementary Exercise for Programming (Coding) [Stacks] Download and unpack (unzip) the file Stacks.rar....
In Java: Initiate empty queue of strings and recreate .isempty, .size, .dequeue, .enqueue methods. //You may...
In Java: Initiate empty queue of strings and recreate .isempty, .size, .dequeue, .enqueue methods. //You may not use the original methods of the stack api to answer. import java.util.NoSuchElementException; import edu.princeton.cs.algs4.Stack; public class StringQueue {    //You may NOT add any more fields to this class.    private Stack stack1;    private Stack stack2;    /**    * Initializes an empty queue.    */    public StringQueue() { //TODO    }    /**    * Returns true if this queue...
Java Program: You will be inserting values into a generic tree, then printing the values inorder,...
Java Program: You will be inserting values into a generic tree, then printing the values inorder, as well as printing the minimum and maximum values in the tree. Given main(), write the methods in the 'BSTree' class specified by the // TODO: sections. There are 5 TODOs in all to complete. Ex: If the input is like ferment bought tasty can making apples super improving juice wine -1 the output should be: Enter the words on separate lines to insert...
public class LinkedStackOfStrings { private Node first; private class Node { private String item; private Node...
public class LinkedStackOfStrings { private Node first; private class Node { private String item; private Node next; } public boolean isEmpty() { return (first == null); } public void push(String item) { // Insert a new node at the beginning of the list. Node oldFirst = first; first = new Node(); first.item = item; first.next = oldFirst; } public String pop() { // Remove the first node from the list and return item. String item = first.item; first = first.next;...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT