Chapter 12 - Programming Exercise #4: Sum of Digits in a String. HINT: You will
ID: 3696217 • Letter: C
Question
Chapter 12 - Programming Exercise #4: Sum of Digits in a String. HINT: You will need to create a utility procedure that allows you to convert from a character to an integer value to allow you to sum the values of the digits in a string. Also, Raptor will not allow you to input a numeric value and treat it as a String input. To work around this limitation, I would recommend putting a character like 'a' somewhere in your input value so Raptor will treat the input as a String data type. Your program should be designed in such a way that it will ignore any non-numeric characters in the input string.
Explanation / Answer
Program:
import org.apache.commons.lang.StringUtils;
public static void main(String[] args)
{
String a = "jklmn489pjro635ops";
int length = a.length();
char c;
int count = 0;
for(int i=0;i<length;i++)
{
c = a.charAt(i);
if(StringUtils.isNumeric(String.valueOf(c)))
{
count = count + Integer.parseInt(String.valueOf(c));
}
}
System.out.println(count);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.