Using Java, write a program that prompts the user to input an integer and then o
ID: 3697584 • Letter: U
Question
Using Java, 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 14.
This has been asked previously but it needs to use while loops, we have not studied arrays yet. And I am stuck trying to get negative numbers to work, I am just getting a 0 in return.
Explanation / Answer
import java.io.*;
import java.util.*;
class Digits
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
int x = sc.nextInt();
int sum =0;
if(x<0){
x *= -1;
}
String number = String.valueOf(x);
System.out.print("Digits are: ");
for(int i = 0; i < number.length(); i++) {
int j = Character.digit(number.charAt(i), 10);
sum +=j;
System.out.print(j + " ");
}
System.out.println(" Sum is: "+sum);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.