gpt4 book ai didi

java - 将 int 转换为 String

转载 作者:行者123 更新时间:2023-12-01 06:43:13 25 4
gpt4 key购买 nike

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);

最后一行内容为:“resultTextField.setText(result);”在提供的代码中,我试图将“结果”变量转换为字符串,但没有成功。我得到的编译错误消息是:

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.

我已经尝试了此处提供的其他“将 int 转换为字符串”问题的答案中提供的几种方法,但它们都不起作用。如何将“结果”转换为字符串?感谢您的帮助。

最佳答案

这会将 int 转换为字符串:

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

编辑:如下所述,无需导入 java.lang,因为它始终可用。

关于java - 将 int 转换为 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29593618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com