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?!

Recommended Answers

All 8 Replies

!hello...this is james..!! hello guys plz help us..

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

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);
     }
}

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.

i also have this kind of problem!! pls help! T_T

@ANDIEniable Please start your OWN THREAD, post the code and the problem.

@NormR1, i meant jefferlyn92's post

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.