Question

I have a two strings containing a certain number (let's say it is not higher than 10).

String five = "5";
String two = "2";

How can I add them up together?

String seven = five + two;

Obviously does not work.

How can I add both numbers to each other and let the output be "7"? Do I have to convert the string first (to an int for example)?

Was it helpful?

Solution

This is not an Android question, this is Java question.

try {
   String seven = Integer.toString(Integer.parseInt(five) + Integer.parseInt(two));
} catch (NumberFormatException nfex) {
// one of the strings was not a number
}

OTHER TIPS

String seven = Integer.toString(Integer.parseInt(five) + Integer.parseInt(two))

Yes you need to convert to int first. Use:

String seven = Integer.toString(Integer.parseInt(five) + Integer.parseInt(two))
int five = 5;
int two = 2;
int seven = five + two;

or

String five = "5";
String two = "2";
int seven = Integer.parseInt(five) + Integer.parseInt(two);

There are various options available.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top