tags:

views:

43

answers:

3

For my assignment I've had to create an ArrayStack, a StackADT, and now I have to make a program to take in a string and output it in reverse.

Now this sounds simple, but I have no idea how to push something into the array. I've been googling the shit out of this and can't find an actual answer that makes sense.

Specifically I'm having trouble linking the main program to the actual array, and then linking the input string to the push().

public class ReverseSentenceMain {

 public static void main (String[] args)
   {


 AssignmentArrayStack stack = new AssignmentArrayStack();
 //private AssignmentArrayStack<String> stack;

 public ReverseSentenceMain()
 {
  stack = new AssignmentArrayStack<Integer>();
 }

   String sentence;
   String result = null;
   String words;
   stack = (T[])(new Object[initialCapacity]);
   Scanner in  = new Scanner(System.in);
   System.out.println("Enter a sentence");


   }
}

I'd appreciate any help and thanks for your time

A: 

You should format the code. Press ctrl+K or use the little 101010 icon.

Anyways. The stack class should have a push method. You need to get the sentence. You could loop through the sentence and then push the characters onto a stack. Once you do that, then you can pop the characters off to print the string in reverse order.

loop through string
    stack.push(string[i])
while(currChar = stack.pop())
    print currChar (or store to another variable)

I believe that will work. Been a while since ive done anything in java.

A stack isn't really an array. Its more like a linked list. It adds an element as the first element in a linked list and then updates the pointer.

Acutally heres a decent example http://www.javacoffeebreak.com/faq/faq0037.html

And i just noticed you want to reverse the sentence and not the word, so do what willcodejavaforfood said and tokenize it with scanner. I remember you can do this. It will read up every whitespace. you get that token and add it to the stack. Some kind of type of concept though.

Matt
A: 

You start scanning by calling next on the scanner.

sentence = in.next();

Then you perform a split on whitespace to divide up the sentence into tokens that you push into your stack. The scanner can do the split for you I think. Look at the Scanner JavaDoc or String JavaDoc for more information.

willcodejavaforfood
A: 

I've been at this for a few days and still can't come up with something.

I don't need a tokenizer or a String.split, not yet anyway.

A simple for/do-while should be enough to push something into the array and since its FILO I ought to be able to use a toString to print what I need (a reveresed string input by the user).

However, I can't even instantiate the stack array in my driver program (if thats the right word for it)

I appreciate teh advice from you guys though.

FailHardwithaVengeance