Answer to Question #289955 in Java | JSP | JSF for Genus

Question #289955

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


1
Expert's answer
2022-01-23T09:40:11-0500


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;
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS