0
fun add(num1: EditText, num2: EditText){
    try {
        num1.toString().toInt()
        num2.toString().toInt()
        answer.setText((num1 + num2).toString())
    } catch (e: NumberFormatException) {
        answer.text = "Input Error"
    }
}

I'm trying to make an integer calculator and have a problem.

answer.setText((num1 + num2).toString())

Here the addition symbol is highlighted in red. The text of the error is huge. What could be the problem?

1
  • @Tenfour04 thx, my bad, I did not change num1 and num2 to variables in the line with the summation Commented Oct 10, 2021 at 12:35

3 Answers 3

2

Use getText() method of EditText to get the value from a EditText.

Change your code like the below

val value1 = num1.getText().toString().toInt()

val value2 = num1.getText().toString().toInt()

answer.setText((value1 + value2).toString())

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

Comments

0

Rafiul and Tenfour04 answer above is correct.. You need to take value from edittext before converting it to string. what you do at you code is convert the whole edittext to string not the value. And I think you need a variable to contain value from edittext. So it will look like this:

var a = num1.getText().toString().toInt()
var b = num2.getText().toString().toInt()
answer.setText((a + b).toString())

4 Comments

There's no necessity for a variable (unless you're using it again), it just keeps the code cleaner.
@HenryTwist iam not sure. I ever see it work but why? it feels nonsense to me :v
What seems nonsense to you? num1.getText().toString().toInt() + num2.getText().toString().toInt()?
ohh.. I think you mean you can just change the value of num2.getText() into int(change data type of this "num2.getText()" into int directly or change its value). I ever do something like that before(my coding mistake) and it works without error. I don't know what happens till now :v
0

num1 and num 2 are EditTexts and you are adding the EditTexts.. this is the main mistake.

From your end you are type casting the values of EditTexts but not getting the values of editText and not saving in the separate variables.

Just get & save the values in separate variables: as @Bobby suggested:

var a = num1.getText().toString().toInt()
var b = num2.getText().toString().toInt()

And then perform addition.

answer.setText((a + b).toString())

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.