将整数转换为字符串时出现问题
我正在尝试将 EditText 字段中的两个数字相加。到目前为止,我有下面的代码,我相信它可以将 EditText 字段“pos1_deg”和“pos1_deg”转换为“pos1_deg”。 'pos2_deg' 转换为整数 deg1 &度2。
deg1 = Integer.parseInt(pos1_deg.getText().toString());
deg2 = Integer.parseInt(pos2_deg.getText().toString());
然后我可以执行以下操作将它们加在一起
degSum = deg1 + deg2
然后 degSum 寄存器保存 deg1 和 deg1 的总和。 2. 到目前为止这是否正确?
然后,为了输出回“结果”EditText,我需要将整数 degSum 更改为字符串。我认为正确的方法是使用下面的代码:
result.setText(degSum.toString());
但是我收到“无法在基本类型 int 上调用 toString()”错误。我做错了什么?
非常感谢您的帮助
I am trying to add two numbers together from EditText fields. So far I have the code below that I believe converts the EditText field 'pos1_deg' & 'pos2_deg' into integers deg1 & deg2.
deg1 = Integer.parseInt(pos1_deg.getText().toString());
deg2 = Integer.parseInt(pos2_deg.getText().toString());
I could then do the following to add them together
degSum = deg1 + deg2
And then the degSum register holds the sum of deg1 & 2. Is this correct so far?
Then to output back to the 'result' EditText I need to change the integer degSum into a string. I thought the correct way was to use the code below:
result.setText(degSum.toString());
However I get an 'Cannot invoke toString() on the primitive type int' error. What am I doing wrong?
Many thanks for any help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
(假设这是Java...)
该消息是正确的。原始值(例如
int
)不能调用它们的方法,因为它们不是对象。相反,关联的方法静态注册在 Integer 类上,因此您应该使用:(此方法还采用可选的第二个参数,可让您指定想要输出数字的基数,因此您可以例如,可以通过调用 Integer.toString(degSum, 16) 来获取十六进制表示形式,这可能不是您现在需要的,但值得记住。)
(Assuming this is Java...)
The message is correct. Primitive values (such as
int
) cannot have methods invoked on them as they are not objects. The associated methods are instead registered on theInteger
class statically, so instead you should use:(This method also takes an optional second argument that lets you specify the base that you want the number output in, so you can get the hexadecimal representation by calling
Integer.toString(degSum, 16)
for example. Probably not what you need right now but worth bearing in mind.)当您将字符串连接到非字符串时,结果是字符串。
例如
When you concatanate a String to a non-String the result is a String.
e.g.
你有没有尝试过:
Have you tried:
你可以尝试做 String.valueOf(deg_sum)
你可以让你的 degSum 不是 int,而是 Integer,这样 toString 方法就可用.
You can try to do String.valueOf(deg_sum)
You can make your degSum not int, but Integer, so the toString method will be available.