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).

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).

import java.util.Scanner;
public class NumberWidth {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); 
int number = sc.nextInt();
System.out.println("Enter an Integer: "+number);
int width = sc.nextInt();
System.out.println("Enter the width: "+width);
        System.out.println("The formatted number is " + format(number, width));
}
    public static String format(int number, int width) {
String num = number + ""; 
int x=num.length();
if ( x < width)
{
  for (int i = width-x; i>0;i--) 
  {
num = 0 + num;
}
}
return num;
}

}

Result:

Enter an Integer: 34
Enter the width: 4
The formatted number is 0034


No comments:

Post a Comment