开发者

push() etc in an ArrayStack

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.开发者_StackOverflow中文版println("Enter a sentence");


   }
}

I'd appreciate any help and thanks for your time


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜