Write a program that prompts the user to input an integer and then outputs both
ID: 648837 • Letter: W
Question
Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, the program should: ouput the individual digits of 3456 as 3 4 5 6 and the sum as 18, output the individual digits of 8030 as 8 0 3 0 and the sum as 11, output the individual digits of 2345526 as 2 3 4 5 5 2 6 and the sum as 27, output the individual digits of 4000 as 4 0 0 0 and the sum as 4, and output the individual digits of -2345 as -2 3 4 5 and the sum as 10.
I have written this:
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Number?");
String input = kb.nextLine();
kb.close();
System.out.printf("The sum of %s is %d%n", input, sum(input));
}
private static int sum(String input) {
int result = 0;
char[] chs = input.replaceAll("[^\d]", "").toCharArray();
for (char c : chs) {
result += Integer.parseInt(String.valueOf(c));
}
return result;
}
}
BUT!! The numbers I input, such as 234, are not showing up like this 2 3 4. They are not spaced out. How do I fix this??
Explanation / Answer
Program:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.