3

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

2
  • There was another question one hour ago that gives an answer: How to convert from integer to String Commented Nov 5, 2010 at 12:25
  • Just to clear something up 'degSum' is not a register, it is a variable. In this context, the term 'register' would mean a specific feature as implemented by the CPU which provides a location which is capable of having operations performed upon it. Commented Jan 23, 2012 at 15:00

4 Answers 4

11

(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 the Integer class statically, so instead you should use:

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

(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.)

Sign up to request clarification or add additional context in comments.

Comments

1

When you concatanate a String to a non-String the result is a String.

e.g.

int deg1 = 5;
int deg2 = 4;
result.setText("" + deg1 + deg2): // passes in "45" (a String)
result.setText("" + (deg1 + deg2)): // passes in "9" (a String)
result.setText(deg1 + deg2); // passes in 9 (an int), compile error

Comments

0

Have you tried:

result.setText(String.valueOf(deg_sum));

Comments

0
  1. You can try to do String.valueOf(deg_sum)

  2. You can make your degSum not int, but Integer, so the toString method will be available.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.