create a method sumOfDigit(String str)
compute and display the sum of the digits found in str

Example:

String str = "1234hello12678";
sumOfDigit(str) -> returns 34

---need some codes guys! can you HELP me?!

iterate through the string, and convert each character into an integer. Then you can find the sum of the integers.

Edited 6 Years Ago by PatrixCR: n/a

Read the API doc for the String class to see how to get each character one at a time.
See the Integer class for how to convert an String character to an integer.

Hey! You can implement this method by using the folloving methods:
public char[] toCharArray() defined in class String
and another method:
public static boolean isDigit(char ch) defined in class Character.
OK lets start writing your method (NOTE: This method throws an instance of DigitNotFoundException which extends class Exceptin):

int sumOfDigits(String str){
  char[] characters=str.toCharArray();
  int sum=0;
  for(int i=0; i<str.length(); i++){
     if(Character.isDigit(characters[i])){
        sum +=characters[i];
     }
  }
  if(sum!=0)
     return sum;
  else
     throw new DigitNotFoundException("There is no any digit in the provided string");
}

The DigitNotFoundException class:

public class DigitNotFoundException extends Exception{
     public DigitNotFoundException(String message){
         super(message);
     }
}

Edited 6 Years Ago by otherdummy: n/a

Apart from violating the "we don't do people's homework for them" rule, the above code does not work as required, so it's doubly unhelpful.
Remember: char is a numeric type.

This article has been dead for over six months. Start a new discussion instead.