[10 marks] (SumDigits.java) Write code that asks the user to enter an integer between 100 and 999. The program finds and displays the three digits in the number. The program also calculates and displays the sum of the three digits. A sample run is shown below:
Enter a number between 100 and 999: 528
The three digits in the number are: 5 2 8
The sum of the three digits is: 15
import java.util.Scanner; public class SumDigits { public static void main(String[] args) { String n; Scanner scan = new Scanner(System.in); System.out.print("Enter a number between 100 and 999: "); n = scan.next(); System.out.print("The three digits in the number are: "); for(int i = 0;i<n.length();i++){ System.out.print(n.charAt(i)+" "); } System.out.println(); int sum = 0; for(int i = 0;i<n.length();i++){ sum += Integer.parseInt(String.valueOf(n.charAt(i))); } System.out.println("The sum of the three digits is: "+sum); } }
Get Answers For Free
Most questions answered within 1 hours.