Click here to Skip to main content
15,884,838 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
import java.util.*;
public class LuckyNum {
	public static void main(String args[])
	{
		String no="1234";
		char ch[]=no.toCharArray();
		int sum=0;
		for(int i=0;i<4;i++)
			{
			sum=sum+(int)ch[i];}
		System.out.println(sum); 
	}

}


What I have tried:

Here i need to convert string to char array so that i can add each element of string(string is numeric) but the expected output 10 and the actual output is 202.
Posted
Updated 27-Jun-19 3:02am

Replace
Quote:
sum=sum+(int)ch[i];

with
sum = sum + (int)(ch[i] - '0');
 
Share this answer
 
Comments
Maciej Los 27-Jun-19 9:37am    
You've been faster then me, Carlo
5ed!
CPallini 27-Jun-19 9:43am    
Thank you very much, Maciej!
MadMyche 27-Jun-19 9:51am    
You've both been +5'd
CPallini 27-Jun-19 10:00am    
Thank you!
What you're doing in your code is converting char into ascii code and then getting the sum of them. That's why your result is equal 202, not 10.

Check this: How can I convert a char to int in Java? - Stack Overflow[^]

Quote:

Java
char x = '9';
int y = Character.getNumericValue(x);   //use a existing function
System.out.println(y + " " + (y + 1));  // 9  10

or

Java
char x = '9';
int y = x - '0';                        // substract '0' code to get the difference
System.out.println(y + " " + (y + 1));  // 9  10
 
Share this answer
 
v2
Comments
CPallini 27-Jun-19 9:42am    
Have my 5, 'slow man' :-D
Maciej Los 27-Jun-19 12:51pm    
Thanks :D
MadMyche 27-Jun-19 9:52am    
You've both been +5'd
Maciej Los 27-Jun-19 12:51pm    
Thank you very much.
Well ... you could take advantage of the character set order, which has '0' then '1', '2', ... '9' in that order.
So subtracting '0' from each character will give you the value:
Java
import java.util.*;
public class Main {
    public static void main (String args[]) {
        String no = "1234";
        char ch[] = no.toCharArray ();
        int sum = 0;
        for (int i = 0; i < 4; i++) {
            sum = sum + (int) (ch[i] - '0');
            } 
        System.out.println (sum);
        } 
    }
But ... I'd strongly suggest you validate your inputs by checking that they are digits first!
 
Share this answer
 
Comments
CPallini 27-Jun-19 9:43am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900