Related questions with answers
Write a method with the following header to format the integer with the specified width. public static String format(int number, int width) The method returns a string for the number with one or more prefix 0s. The size of the string is the width. For example, format(34, 4) returns 0034 and format(34, 5) returns 00034. If the number is longer than the width, the method returns the string representation for the number. For example, format(34, 1) returns 34. Write a test program that prompts the user to enter a number and its width and displays a string returned by invoking format(number, width).
Solution
Verifiedimport java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number and a width: ");
int number = input.nextInt();
int width = input.nextInt();
System.out.print("Formatted representation: " + format(number, width));
}
public static String format(int number, int width)
{
String numString = Integer.toString(number);
if (numString.length() < width)
{
for (int i = width - numString.length(); i > 0; i--)
{
numString = 0 + numString;
}
}
return numString;
}
}
Step 1.1: Create a method format that returns a formatted string with
prefixed 0s
Step 1.2: Convert a number to the string to conduct operations on it
Step 1.3: If the string’s length is smaller than entered width, add
leading zeros in the width - length space
Step 1.4: If the string’s length is equal or greater than width, just
return the string representation of the number
Step 2.1: Prompt the user to enter a number and a width
Step 2.2: Pass values to the method and display the formatted string
Create a free account to view solutions
Create a free account to view solutions
Recommended textbook solutions

Intro to Java Programming, Comprehensive Version
10th Edition•ISBN: 9780133761313Y. Daniel Liang
Fundamentals of Database Systems
7th Edition•ISBN: 9780133970777Ramez Elmasri, Shamkant B. Navathe
Introduction to Algorithms
3rd Edition•ISBN: 9780262033848Charles E. Leiserson, Clifford Stein, Ronald L. Rivest, Thomas H. Cormen
Introduction to Algorithms
4th Edition•ISBN: 9780262046305Charles E. Leiserson, Clifford Stein, Ronald L. Rivest, Thomas H. CormenMore related questions
- computer science
- algebra
1/4
- computer science
- algebra
1/7