簡體   English   中英

在Java中打印數字的模式序列

[英]Print a pattern sequence of numbers in Java

我需要編寫一個名為printOnLines()的方法,該方法接受兩個參數:整數n和整數inLine,並在一行中的每個inLine上打印n個整數。

for n = 10, inLine = 3:
1, 2, 3
4, 5, 6
7, 8, 9
10

我的電話是(10,3) 這是我的代碼:

public static void printOnLines(int n, int s) {
        for(int i=1; i<=s; i++) {
            for(int j=1; j<=n-1; j++) {
                System.out.print(j + ", ");
            }
        System.out.println();
        }
    }
}

我相信有兩個錯誤:

  1. 我需要刪除輸出中出現的最后一個逗號。
  2. 我需要在每一行中放置3個數字,直到達到10。

用這個:

public static void printOnLines(int n, int s){
     StringBuilder builder = new StringBuilder();
     for(int i = 1; i <= n; i++){
         builder.append(i);
         if(i % s == 0)builder.append("\n");
         else builder.append(", ");
     }
     System.out.println(builder.toString().substring(0,builder.toString().length() - 2));
}

我不會發布完整的解決方案,因為這顯然是家庭作業。 但是,如果不允許使用if語句或三元運算符,這就是我會做的事情。

  • 使外循環的索引從0開始,並在每次迭代中均由s而不是1所增加(因此在示例中為0、3、6、9)。
  • 在每次迭代中打印兩個循環索引的總和。
  • 在內部循環外的每一行上打印最后一個數字,不帶逗號。

編輯

OK,應@localhost的要求,這是我的解決方案。

public static void printOnLines(int n, int s) {
    for (int i = 0; i < n; i += s) {
        int j;
        for (j = 1; j < s && i + j < n; j++) {
             System.out.print(i + j + ", ");
        }
        System.out.println(i + j);
    }
}

我認為您已經必須提交家庭作業,因此我將按照以下方式進行:

class printonlines {
public static void main(String[] args) {        
    printOnLines(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
}

public static void printOnLines(int n, int s) {     
    for(int i=1; i<=n; i++) {  // do this loop n times
        if ( (i != 1) && (i-1)%s == 0 ) {  // if i is exactly divisible by s, but not the first time
            System.out.println(); // print a new line
        }
        System.out.print(i);
        if (i != n) {  // don't print the comma on the last one
            System.out.print(", ");
        }
    }
    }
}

哦,您不想使用任何if語句。 像要求您做的那樣,從“技巧”中真正學到的只是一個技巧,而不是如何編寫容易理解的代碼(即使您自己需要稍后調試時也是如此)。

無論如何, if按照@DavidWallace的答案的建議,這是我不那么容易理解但更棘手的代碼。 我敢肯定有人可以做得更整潔,但這是15分鍾內我能做的最好的事情。

class printonlineswithnoifs {
    public static void main(String[] args) {

        printOnLines(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
    }

    // i 012012012
    // j 000333666
  // i+j 012345678

    public static void printOnLines(int n, int s) {

        int i = 0;
        int j = 1;
        for (; j <= n; j+=s) {
            for (; i < (s-1) && (j+i)<n; i++) {

                 System.out.print((i+j) + ", ");
            }
            System.out.println(i+j);
            i=0;
        }
    }
}

這是您想要的代碼示例。

public static void printOnLines(int n, int s) {
    for (int i = 1; i < n; i++) {
        System.out.print(i + ",\t");
        if (i % 3 == 0) System.out.println();
    }
    System.out.println(n);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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