Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a word with a Stack

Tags:

java

I am new here and in programming as well. I am trying to study other topics alone since my instructor isn't enough help when I have a question so here it goes. I want reverse a word with a generic Stack.

My pop,push,isEmpty and peek methods work (I tested them with a simpler program I made before I tried it on this one.) and the output seems to be giving me the reversed word char by char but always giving me a null before each char!

My questions are: Why is this happening? And even though I have an expandCapacity method to work when the capacity is at 9 but it doesn't apply when the input passes the limit.


Here's my code

package Stack;

import java.util.Scanner;

public class ReverseDriver<T> {
    private static String out;
    private static String in;

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter your sentence: ");
        in = input.nextLine();
        int size = in.length();

        ArrayStack<Character> revStack = new ArrayStack<>(size);

        for (int i = 0; i < in.length(); i++) {

            char u = in.charAt(i);
            revStack.Push(u);
            if (in.length() > 9) {

                revStack.expandCapacity();

            }
        }

        while (!revStack.IsEmpty()) {
            char u = revStack.Pop();
            out = out + u;
            System.out.flush();
            System.out.print(out);

        }

    }
}

Here's the Output

run:
Enter a word: 
word
nullr
nullro
nullrow
Exception in thread "main" java.lang.NullPointerException
    at Stack.ReverseDriver.main(ReverseDriver.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)

EDIT: here's the methods that I said that were working.

@Override
public void Push ( T element)
   {
     if (count == stack.length){
         expandCapacity();
     }
      stack[++count] = element;


       //System.out.println(count);
   }



  @Override
   public String toString()
   {
      String result = "<top of stack>\n";

      for (int index=count-1; index >= 0; index--){
         result += stack[index] + "\n";
      }
      return result + "<bottom of stack>";
   }





         @Override
    public boolean IsEmpty()
    { //Checks if array is empty
        if(count == 0){
        System.out.println("Nothing");
        }

         return count == 0;


    }


 public  T Pop() 
      {

             T output; 

         output =  (stack[count - 1]);
         count--;


         return(output);

      }



 @Override
    public T Peek()
      {
          //looks at the object at the top of this stack without removing it
     //from the stack.

          if(stack.length == 0){
         // {
      System.out.println("Cant peek a ghost");

          }

         return(stack[--count]);

      }
         // else
         // {
     // System.out.println( stack[count-1]);

         // }

     // }

      @Override
    public int Size()
    {
        //Sets the size of this vector
        if(stack.length == 0){
            System.out.println("Nothing inside");
        }

       System.out.println("The array's size is : " + count);
        return count;


    }



}
like image 481
Jorge A Vega Vigo Avatar asked Mar 08 '13 19:03

Jorge A Vega Vigo


3 Answers

private static String out;

The value in out is null.

out = out + u;
// This is null = null + u;

Hence the null at the beginning of your output.

You simply need to create a new String object to give out an initial value:

 private static String out = "";
like image 146
christopher Avatar answered Nov 01 '22 17:11

christopher


i'm not sure why you need the ExpandCapacity bit there, this works aswell:

public static void main(String[] args)
    {       

    String word ="reverse please";      
    Stack<Character> chStack = new Stack<Character>();      
    for (int i = 0; i < word.length(); i ++)
    {       
        chStack.push(word.charAt(i));       
    }

    String out = "";
    while (chStack.size() != 0)
    {
        out += chStack.pop();
        System.out.println(out);

    }               
}
like image 27
Thousand Avatar answered Nov 01 '22 15:11

Thousand


There are a few notes:

  • You are not writing a generic class so drop .
  • Leave the iteration to for as much as possible.
  • Try using Java standard classes as much as possible, in this case Stack instead of ArrayStack.
  • You don't need to resize the stack, it will handle its size dynamically as you put more data in.
  • You should write the string once you are done creating it not once in every step.
  • Appending strings using + is very inefficient. Use StringBuilder.
  • Use methods they make your code readable.

Heres the code:

import java.util.Scanner; 
import java.util.Stack;

public class ReverseDriver {
  public static String reverse(String string) {
    Stack<Character> revStack = new Stack<Character>();
    for (char c : string.toCharArray()) {
      revStack.push(c);
    }
    StringBuilder builder = new StringBuilder();
    while(!revStack.isEmpty()){
      builder.append(revStack.pop());
    }
    return builder.toString();
  }

  public static void main(String[]args){
    Scanner input = new Scanner(System.in);
    System.out.println("Enter your sentence: ");
    String in = input.nextLine();
    System.out.println(reverse(in));
  }
}
like image 40
siavach Avatar answered Nov 01 '22 16:11

siavach