سؤال

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

هل كانت مفيدة؟

المحلول

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
}

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top