I am new to java dev. I want to add numbers in an editText. i.e if user types in 15 in editText, it should add the numbers 1 + 5 giving the result 6. Is there a function for it in java. In C# it is ToCharArray() but I don't know what it's called in java. Thanks
2 Answers
you can use
String str = "15";
char[] cArray = str.toCharArray();
int sum = 0;
for (char c : cArray)
sum += Character.digit(c, 10);
6 Comments
artist
I am using the above code, but the app seems to crash.Also I am getting error (cannot parse int here) when I try to use sum += Integer.parseInt(c) Any help will be great.
artist
Also how can i put the result in a textview. I am using textv.setText(sum) but it doesn't seems to be working.
Bala R
@artist try my edit for the error. As far as the textView, textv.setText(sum.toString()) should work.
artist
still says that application has stopped unexpectedly.
artist
It works now. I want to know what does 10 stands for in the above code sum += Character.digit(c, 10); Thanks
|