0
private JTextField resultTextField;
resultTextField.setText(" "); ...

private class InputListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        Stack<Integer> operandStack = new Stack<Integer>();
        Stack<Character> operatorStack = new Stack<Character>();

        String input = inputTextField.getText();

        StringTokenizer strToken = new StringTokenizer(input, " ", false);


        while (strToken.hasMoreTokens())
        {
            String i = strToken.nextToken();
            int operand;
            char operator;

            try
            {
                operand = Integer.parseInt(i);
                operandStack.push(operand);
            }
            catch (NumberFormatException nfe)
            {
                operator = i.charAt(0);
                operatorStack.push(operator);
            }
        }
        int result = sum (operandStack, operatorStack);
        resultTextField.setText(result);

The last line that reads: "resultTextField.setText(result);" in the code provided, I'm trying to convert the 'result' variable to a String but having no success. The compile error message I get is:

PrefixExpression.java:96: error: method setText in class JTextComponent cannot be applied to given types;
          resultTextField.setText(result);
                         ^
  required: String
  found: int
  reason: actual argument int cannot be converted to String by method invocation conversion.

I've tried several methods already provided in answers to other 'convert int to String' questions in here, but none of them work. How do I convert 'result' to a String? Thanks for your help.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
Jeremy
  • 113
  • 2
  • 14

4 Answers4

4

This will convert an int to a string:

resultTextField.setText(Integer.toString(result));

EDIT: As mentioned below there is no need to import java.lang as it will be available always.

druidicwyrm
  • 480
  • 2
  • 11
3

You can use the Integer.toString(number) or String.valueOf(number) function. This function can take an integer and turn it into a String. Try adding:

String numResult = Integer.toString(result);

or

String numResult = String.valueOf(result);
MLavrentyev
  • 1,827
  • 2
  • 24
  • 32
2

You could do a hack

resultTextField.setText(result + "");
Moishe Lipsker
  • 2,974
  • 2
  • 21
  • 29
1

Just do this: (new Integer(result)).toString() and you should be OK.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159