String st="1a2b3j4";
char ar[]=st.toCharArray();
int sum=ar[0]+ar[2];//how to add the numbers
when i try to add its taking ASCII values
how to convert chat'1' to integer
You just must convert the character to String and then use something like this:
int sum = Integer.parseInt(stringNum1) + Integer.parseInt(stringNum2);
NumberFormatException if stringNum1 or stringNum2 is an alphabet. you need to handle that case.If you want to convert character ASCII numeric value, just cast your char as an int
like char character = arr[0];
int asciiValue = (int) character;
Are you looking for this?
String st = "1a2b3j4";
char ar[] = st.toCharArray();
int sum = 0;
for (int i = 0; i < ar.length; i++) {
sum += (ar[i] - '0');
}
System.out.println(sum); // prints 167 (1 + 49 + 2 + 50 + 3 + 58 + 4)
If you want to consider the ASCII value for the alphabets but the numeric digits itself, then you can try as following.
String st = "1a2b3j4";
char ar[] = st.toCharArray();
int sum = 0;
for (int i = 0; i < ar.length; i++) {
if (ar[i] >= '0' && ar[i] <= '9') {
sum += (ar[i] - '0');
} else {
sum += ar[i];
}
}
System.out.println(sum); // prints 311 (1 + 97 + 2 + 98 + 3 + 106 + 4)
Note that, ASCII values for 1,a,2,b,3,j,4 are 49,97,50,98,51,106,52.
just add (int) at the beginning of each array elements. ie int sum=(int)ar[0]+(int)ar[2]; hope this helps;
Integer.parseInt(value)? I'm rather confused what the actual question is, sorry.'0'.