简体   繁体   English

如果输入 n 并且输出是 n 位数字,并且以 (n-1)0 开头,并且从 1 到 (n-1)9?

[英]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输入:n=3

output: 001 to 999输出:001 到 999

input:n=4输入:n=4

output:0001 to 9999输出:0001 到 9999

input:n=2输入:n=2

output:01 to 99输出:01 到 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感谢@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);
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 第(N-2)和(N-1)的第N个输出和 - Nth output sum of (N-2)th and (N-1)th 打印数字系列 1,n,2,n-1,3,n-2,... 系列的逻辑应该是 1 到 n(给定的输入) - logic to print a number series 1,n,2,n-1,3,n-2,... series should be 1 to n(the input given) 给定数字n作为输入,返回长度为n的新字符串数组,其中包含字符串“ 0”,“ 1”,“ 2”,依此类推,直到n-1 - Given a number n as input, return a new string array of length n, containing the strings “0”, “1”, “2” so on till n-1 在 n-1 天内将 n 人以不同的对分配的算法 - Algorithm to distribute n people in unique pairs over n-1 days 二进制算术:为什么hash%n等价于hash&(n-1)? - Binary arithmetic: why hash%n is equivalent to hash&(n-1)? (Java)递归函数:使用n-1和n + 1 - (Java) Recursive Functions: using n-1 and n+1 检索for循环中每个位置的“n-1”和“n + 1”元素 - Retrieve “n-1” and “n+1” element of each position in a for loop n个字符之后以及之后的每n-1个字符之后的空格 - Whitespace after n character and after every n-1 character following 当n为2^k时,如何证明m%n等价于m&amp;(n-1)? - How to prove m%n is equivalent to m&(n-1) when n is 2^k? 我如何编写递归方法来求和 x^n + x^(n-1) + x^(n-2)? - How do i write a recursive method to sum x^n + x^(n-1) + x^(n-2)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM