Luke J Houghton Luke J Houghton - 26 days ago 16
Java Question

Need help printing strings in reverse order using stack (see details)

I've managed to get my code to compile however I'm trying to make a program that takes the user input and uses the push() method to add that string to the stack.I am then using other methods to reverse the order of input. For example the user inputs a few strings :
"Hello"
"World"
"!"
And then once the user has typed "end" as an input the program will stop pushing to the stack and print in reverse order like so:
"!"
"World"
"Hello"

Here is my code below:

public class stackReversal {

private Node first = null;

private class Node {
private String item;
private Node next;
}

public boolean isEmpty() {
return (first == null);
}

public void push(String s) {
Node node = new Node();
node.item = s;
node.next = first;
first = node;
}

public String pop() {
if (first == null)
throw new RuntimeException("Stack Empty!");
String result = first.item;
first = first.next;
return result;
}

public String popString() {
String result = "";
Node current = first;
while (current != null) {
result += current.item;
current = current.next;
}
return result;
}

public String toString() {
StringBuilder nodes = new StringBuilder();
Node node = first;
while (node != null) {
nodes.append(node.item);
node = node.next;
}
if (isEmpty()) {
return "";
} else {
return nodes.toString().substring(0, nodes.toString().length() - 4);
}
}

public static void main(String[] args) {
stackReversal s = new stackReversal();
Scanner input = new Scanner(System.in);
System.out.print("Enter strings:");
String in = input.nextLine();
while (!in.equals("end-of-input")) {
s.push(in);
if (in.equals("end"))
break;
}
System.out.println("Strings:" + s);
}
}

Answer

Your loop simply didn't work and you didn't have any end condition, to it.

Change your main method to the following:

public static void main(String[] args)
{
    StackReversal s = new StackReversal();
    Scanner input = new Scanner(System.in);
    System.out.print("Enter strings:");
    String in = "";
    while (!in.equals("end"))
    {
        in = input.nextLine();
        if (in.equals("end"))
            break;
        else
            s.push(in);
    }
    System.out.println("Strings:" + s);
}
  1. end-of-string and end should be the same condition. So just end
  2. input.nextLine(); needs to be in the loop and assigned to in each time
  3. s.push(in); should be in the else statement to avoid adding end to the stack.

If this has helped you and answered your question, please flag as the correct answer and upvote :)

Comments