2 Replies - 399 Views - Last Post: 18 November 2009 - 10:28 PM Rate Topic: -----

#1 peterjsousa  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 17-December 08

Loops Within A Stack

Posted 18 November 2009 - 05:54 PM

Hi all,

I'm trying to edit the program below to do the following: In stead of using a built in Java Conversion method, I need to use a loop that pushes onto a stack the same thing that is sent as a parameter to the original recursive call and, when there would be no more recursive calls, use another loop to pop items off the stack until it is empty. I am trying to convert an Integer to binary using the stack.

package project2;

import java.util.Stack;

public class Main

{
	public static void main(String[] args)
	{
		String binary;
		int number = 3;
		Stack myStack = new Stack();
		myStack.push(number);

		do
		{
			binary = Integer.toBinaryString(number);
			myStack.pop();
			System.out.println("Byte: " + binary);
		}
		while ( myStack.isEmpty() == false );
	}
}



Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: Loops Within A Stack

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: Loops Within A Stack

Posted 18 November 2009 - 07:05 PM

You push only one element on the stack... why making a loop to pop them
Also the pop() return what was pushed you do not save what it returns

should rather look like that (if ever you decide to push more than one element)

		String binary;
		int number = 3;
		Stack<Integer> myStack = new Stack<Integer>();
		myStack.push(number);

		while(!myStack.isEmpty())
		{
			binary = Integer.toBinaryString(myStack.pop());
			System.out.println("Byte: " + binary);
		}


Was This Post Helpful? 0
  • +
  • -

#3 peterjsousa  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 17-December 08

Re: Loops Within A Stack

Posted 18 November 2009 - 10:28 PM

Thanks very much for your help!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1