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
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; } /*...
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...
Using SLLStack.java, implement an application, LineReverser.java, that reads a line from keyboard (user enters one line),...
Using SLLStack.java, implement an application, LineReverser.java, that reads a line from keyboard (user enters one line), insert each separate word into the stack, and read/print on the screen. So, if the user enters: This is a test the application output should be: test a is This. This is SLLSTACK.java below package linked_lists; public class SLLStack {    //instance variabels    private SLLNode top;    private int numOfItems;       //constructors    public SLLStack() {        top = null;   ...
Use Java: Also: Please include screenshots if possible. Create a class called AbstractStackTest. Write an abstract...
Use Java: Also: Please include screenshots if possible. Create a class called AbstractStackTest. Write an abstract method called makeStack that returns a Stack of Strings. Use the Stack interface as the return type, not a specific implementation! Write a class named NodeStackTest that extends your AbstractStackTest class. Implement the makeStack method to return a NodeStack. Repeat parts 1 and 2 for the Queue interface and the NodeQueue implementation. Write a new stack implementation, ArrayStack. It should be generic and use...
Stack2540Array import java .io .*; import java . util .*; public class Stack2540Array { int CAPACITY...
Stack2540Array import java .io .*; import java . util .*; public class Stack2540Array { int CAPACITY = 128; int top ; String [] stack ; public Stack2540Array () { stack = new String [ CAPACITY ]; top = -1; } 1 3.1 Implement the stack ADT using array 3 TASKS public int size () { return top + 1; } public boolean isEmpty () { return (top == -1); } public String top () { if ( top == -1)...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue class . Call your class Queue. it must be a template class. public class Queue { } I have put a driver program in the module . It is called CircularQueue.java This driver program should then run with your Queue class (no modifications allowed to the driver program). Your Queue class should have at least the following methods: one or more constructors, enqueue, dequeue,...
Task 1: You will modify the add method in the LinkedBag class.Add a second parameter to...
Task 1: You will modify the add method in the LinkedBag class.Add a second parameter to the method header that will be a boolean variable: public boolean add(T newEntry, boolean sorted) The modification to the add method will makeit possible toadd new entriesto the beginning of the list, as it does now, but also to add new entries in sorted order. The sorted parameter if set to false will result in the existing functionality being executed (it will add the...