Andrew Ulanov
Andrew Ulanov

Reputation: 9

Adding two numbers from EditText fields

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?

Upvotes: 0

Views: 728

Answers (3)

Hafiza
Hafiza

Reputation: 860

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

Upvotes: 0

Bobby Anggunawan
Bobby Anggunawan

Reputation: 44

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

Upvotes: 0

Rafiul
Rafiul

Reputation: 2020

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

Upvotes: 2

Related Questions