I created a console program in jcreator (java) which asks the user to enter a number in string and converts that string value into char array and then converts each char array into an integer which I also stored each as an array and then adds all the value from integer array and prints the total on the screen. Someone says its not the solution he is looking for and that I shouldnt use string and I need to focus on the integer value. Is there any other way of doing this as unlike my program? if there is, can you show me the code you have used? thank you.

Dani AI

Generated

Both approaches in the thread are valid; ’s original char-array conversion and ’s suggestions (read as an integer, or parse each character) each solve the problem. Choice depends on constraints: whether the input may contain non-digits, signs, or values larger than an int, and whether readability or micro‑performance matters.

For Java, prefer extracting digit values from chars without allocating a temporary String per character. Character.getNumericValue(c) handles Unicode digits safely; for plain ASCII digits c - '0' is fastest. Example pattern:

String s = /* input token */;
int sum = 0;
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    int d = Character.getNumericValue(c); // returns -1 for non-digits
    if (d >= 0 && d <= 9) sum += d;
}

Character.getNumericValue is documented in the Java API: Character.getNumericValue. For very large numeric strings that exceed 64-bit, switch to BigInteger to avoid overflow: BigInteger. Also handle input parsing errors (invalid tokens) and leading signs explicitly; Scanner.nextInt() throws exceptions on bad input and removes the need to validate digits but fails for huge numbers.

A compact Python idiom (not shown earlier in the thread) is convenient for digit-sum tasks:

s = input().strip()
total = sum(int(c) for c in s if c.isdigit())
print(total)

See str.isdigit() and int() in the Python docs for behavior with Unicode digits: str.isdigit and int().

In short: use string-based digit extraction when the task is “sum of digits” and input can contain non-digit symbols; use numeric input and modulus when working with arithmetic on values that fit primitive ranges.

Member Avatar for Member #887084

Although I disagree with "someone", using Integer or String is suitable in this case.

System.out.print("Value: ");
		int value = new Scanner(System.in).nextInt();
		
		int sum = 0;
		while (value > 0) {
			sum += value % 10;
			value /= 10;
		}
		
		System.out.println(sum);
System.out.print("Value: ");
		String value = new Scanner(System.in).next();
		
		int sum = 0;
		for (char i : value.toCharArray()) 
			sum += Integer.parseInt(Character.toString(i));

		System.out.println(sum);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.