簡體   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?

我已經嘗試了很多次這個程序,直到現在我都沒有得到正確的輸出,請幫助我解決這種類型的程序。

輸入:n=3

輸出:001 到 999

輸入:n=4

輸出:0001 到 9999

輸入:n=2

輸出: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
    }
}

您可以使用此代碼

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

感謝@RalfRenz

你可以試試下面的代碼嗎?

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM