简体   繁体   中英

If enter n is input and the output is in n digits and starting with (n-1)0 with 1 to (n-1)9's?

I have tried this program many times I didn't get the proper output till now please help me to solve this type of program.

input:n=3

output: 001 to 999

input:n=4

output:0001 to 9999

input:n=2

output:01 to 99

public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    int number = scan.nextInt();
    int sum=1,result=0;
    while(number!=0)
    {
        result=result+(9*sum);
        sum=sum*10;
        number--;
    }
    System.out.println(result);
    for(int i=1;i<=result;i++)
    {
        System.out.printf("%02d ",i);//here i manually mentioned the %02d  but i want to take user input
    }
}

You can use this code

    int number = 3;
    String mask = "%0" + (number) + "d%n";
    int max = (int)Math.pow(10, number)-1;

    for (int x = 1; x <= max; x++)
        System.out.printf(mask, x); 

thanks to @RalfRenz

Can you try below code ?

class Main
{
public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    int num = scan.nextInt();
    String masked = "%0" + (num) + "d%n";
    int max = (int)Math.pow(10, num)-1;
    for (int k = 1; k <= max; k++)
        System.out.printf(masked, k);
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM