Question

Write a Java program to return the sum of the digits present in the given string....

Write a Java program to return the sum of the digits present in the given string. If there is no digit, the sum return is 0.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.Scanner;

public class SumDigitsInString {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a string: "); // ask user for a string
        String s = in.nextLine(); // read string from user
        int sum = 0; // create sum variable and initialize it with 0
        for (int i = 0; i < s.length(); i++) {  // go through all characters of string
            if (Character.isDigit(s.charAt(i))) { // if character is a digit
                sum += s.charAt(i) - '0';   // then add that digit to sum
            }
        }
        System.out.println(sum);    // finally print the calculated sum
    }
}

Add a comment
Know the answer?
Add Answer to:
Write a Java program to return the sum of the digits present in the given string....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT