1
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

5
  • 3
    What does this have to do with C++, Spring, Hibernate, and Java EE? Commented Dec 22, 2016 at 18:33
  • //how to convert char '1' and '2' to integers ? Commented Dec 22, 2016 at 18:33
  • 3
    Are you looking for Integer.parseInt(value)? I'm rather confused what the actual question is, sorry. Commented Dec 22, 2016 at 18:34
  • Consider the distance from any digit to '0'. Commented Dec 22, 2016 at 18:34
  • Use loop, it will make it easier. Commented Dec 22, 2016 at 18:35

4 Answers 4

2

You just must convert the character to String and then use something like this:

int sum = Integer.parseInt(stringNum1) + Integer.parseInt(stringNum2);
Sign up to request clarification or add additional context in comments.

1 Comment

this will raise NumberFormatException if stringNum1 or stringNum2 is an alphabet. you need to handle that case.
0

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;

1 Comment

That will get the ASCII value, not the numeric "digit" value.
0

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.

Comments

-1

just add (int) at the beginning of each array elements. ie int sum=(int)ar[0]+(int)ar[2]; hope this helps;

1 Comment

Please try to markdown your code and provide more information for further detail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.