HTML

html content help to improve the coding

Thursday, 13 September 2012

How do you write a java program that sums the digits of an integer and optimizes it to single digit?


import java.util.*; 
public class Digit 

public static void main(String[] args) 

Scanner sc = new Scanner(System.in); 
System.out.print("Enter Number:"); 
String r = sc.nextLine(); 
int[] b = new int[r.length()]; 
String [] a = new String[r.length()]; 
int k = 0; 
System.out.println("\n"); 
System.out.print("The Digits of the number are: "); 
for (int i = 0; i < r.length(); i++) 

a[i] = r.substring(i,i+1); 
System.out.print(a[i]); 
System.out.print(" "); 
k = k + Integer.parseInt(a[i]); 


System.out.println("\n"); 
System.out.print("The sum of the digits is: "); 
System.out.println(k); 



Output: 


C:\>java Digit 

Enter Number:123456789 


The Digits of the number are: 1 2 3 4 5 6 7 8 9 

The sum of the digits is: 45 

No comments:

Post a Comment