I've got a small little program that I'm trying to write that converts a base10 number to a base2. For some reason my instructor wants us to use stack on this. I've got most of it done but I'm having trouble trying to get the stack converted to an int so that I can pass it back as one number. Somehow I have to Pop the top of my "stack1" in my int "base2". Can somebody show me how to do this??
Thanks
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class BaseConversion extends JApplet {
private JLabel text1, text2;
private JTextField userField1, userField2;
private JButton convertButton, clearButton;
public void init() {
text1 = new JLabel("Input a number in base ten: ");
text2 = new JLabel("Your number in base two: ");
text1.setForeground(Color.YELLOW);
text2.setForeground(Color.YELLOW);
userField1 = new JTextField(15);
userField2 = new JTextField(15);
convertButton = new JButton("Convert");
clearButton = new JButton("Clear");
EndingListener buttonEar_convert = new EndingListener();
convertButton.addActionListener(buttonEar_convert);
EndingListener buttonEar_clear = new EndingListener();
clearButton.addActionListener(buttonEar_clear);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.setBackground(Color.BLUE);
c.add(text1);
c.add(userField1);
c.add(text2);
c.add(userField2);
c.add(convertButton);
c.add(clearButton);
}
private int stackreturn ( int base10 ){
int base2, tostack;
Stack stack1 = new Stack();
if (base10/2!=0 || base10==1){
while(base10!=1){
tostack = base10%2;
stack1.push(new Integer(tostack));
base10 = base10/2;
}
stack1.push(new Integer(1));
}
while (! stack1.empty())
{
stack1.pop();
}
return base2;
}
public class EndingListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Convert"))
{
int base10, base2;
String message;
message = userField1.getText();
BaseConversion test = new BaseConversion();
base10 = Integer.parseInt( message );
base2 = test.stackreturn(base10);
message = Integer.toString(base2);
userField2.setText(message);
}
if (e.getActionCommand().equals("Clear"))
{
userField1.setText("");
userField2.setText("");
}
}
}
}