Write a program to take a number as input then display the digits in the following format:
For example:
Input : 2315
Output: 5+1+3+2=11
Using following method prototype:
String generate(int n)
Using java.util package only
import java.util.*;
public class App {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
System.out.print("Enter the number: ");
int n = keyBoard.nextInt();
System.out.println(generate(n));
keyBoard.close();
}
static String generate(int n) {
String result = "";
int sum = 0;
while (n > 0) {
int d = n % 10;
if (n > 2) {
result += d + " + ";
} else {
result += d;
}
sum = sum + d;
n = n / 10;
}
result += " = " + sum;
return result;
}
}
Comments
Leave a comment