与数字的空的金刚石形状在Java

时间:2017-06-19 23:38:34

标签: java

所以我被问到这个问题,我只能解决代码的顶部,我被困在底部。

编写一个名为EmptyDiamond.java的Java程序,其中包含一个采用
的方法 整数N并在2N - 1行打印空菱形,如下所示 当n = 3时的样本输出。

   1
  2 2
 3   3
  2 2
   1

到目前为止,这是我的代码:

    public static void shape(int n){


//TOP PART


        for(int i=1; i<=(n-1) ; i++){
            System.out.print(" ");
        }
        System.out.println(1);

        for(int i=2; i<=n; i++){
            for(int j=1; j<=(n-i); j++){
                System.out.print(" ");
            }
            System.out.print(i);

            for(int j=1; j<=2*i-n+1; j++){
                System.out.print(" ");
            }
            System.out.println(i);
        }

//BOTTOM PART(The messed up part)

        for(int i=n+1; i<=2*n-2; i++){

            for(int j=1; j<=n-i; j++){
                System.out.print(" ");
            }
            System.out.print(i);

            for(int j=1; j<=n; j++){
                System.out.print(" ");
            }


            System.out.print(i);
        }
        for(int i=1; i<=(n-1) ; i++){
            System.out.print(" ");
        }
        System.out.println(1);
    }
    public static void main(String[]args){
        shape(4);
    }

8 个答案:

答案 0 :(得分:0)

以下是打印空钻石的程序:

int n = 3; //change the value of n to increase the size of diamond
int upperCount = 1;
for(int i=n; i>=1; i--){

    for(int j=i; j>=1; j--){
       System.out.print(" ");
    }
    System.out.print(upperCount);

    for(int j=0; j<=upperCount-2; j++){
       System.out.print(" ");
    }

    for(int j=0; j<=upperCount-2; j++){
       System.out.print(" ");
    }

    if(upperCount!=1){
       System.out.print(upperCount);
    }

    upperCount++;
    System.out.print("\n");
}

int lowerCount = n-1;
for(int i=1; i<=n-1; i++){

    for(int j=0; j<=i; j++){
        System.out.print(" ");
    }
    System.out.print(lowerCount);

    for(int j=0; j<=lowerCount-2; j++){
       System.out.print(" ");
    }

    for(int j=0; j<=lowerCount-2; j++){
       System.out.print(" ");
    }

    if(lowerCount!=1){
       System.out.print(lowerCount);
    }

    lowerCount--;
    System.out.print("\n");
}

在代码的底部进行以下更改:

int lowerCount = n-1;
for(int i=n-1; i>=2; i--){
    for(int j=1; j<=(n-i); j++){
       System.out.print(" ");
    }
    System.out.print(i);

    for(int j=1; j<=lowerCount; j++){
       System.out.print(" ");
    }
    System.out.print(i);
    lowerCount-=2;
}

答案 1 :(得分:0)

您可以在从 -nn 的行和列上使用两个嵌套的 for 循环打印带有数字的空菱形形状。当 iAbs + jAbs == n:

时获得菱形形状
int n = 2;
for (int i = -n; i <= n; i++) {
    // absolute value of 'i'
    int iAbs = Math.abs(i);
    for (int j = -n; j <= n; j++) {
        // absolute value of 'j'
        int jAbs = Math.abs(j);
        // empty diamond shape
        System.out.print(iAbs + jAbs == n ? jAbs + 1 : " ");
        if (j < n) {
            System.out.print(" ");
        } else {
            System.out.println();
        }
    }
}

输出:

    1    
  2   2  
3       3
  2   2  
    1    

你可以分别定义widthheight

int m = 4;
int n = 2;
int max = Math.max(m, n);
for (int i = -m; i <= m; i++) {
    // absolute value of 'i'
    int iAbs = Math.abs(i);
    for (int j = -n; j <= n; j++) {
        // absolute value of 'j'
        int jAbs = Math.abs(j);
        // empty diamond shape
        System.out.print(iAbs + jAbs == max ? jAbs + 1 : " ");
        if (j < n) {
            System.out.print(" ");
        } else {
            System.out.println();
        }
    }
}

输出:

    1    
  2   2  
3       3
         
         
         
3       3
  2   2  
    1    

另见:
Filling a 2d array with numbers in a rhombus form
How to print a diamond of random numbers?

答案 2 :(得分:0)

java-11

使用作为 Java-11 一部分引入的 String#repeat,您可以使用单循环来实现。

public class Main {
    public static void main(String[] args) {
        int n = 3;
        for (int i = 1 - n; i < n; i++) {
            int x = Math.abs(i);
            System.out.println(" ".repeat(x) + (n - x)
                    + " ".repeat(Math.abs((n - x) * 2 - 3))
                    + ((i == 1 - n || i == n - 1) ? "" : (n - x)));
        }
    }
}

输出:

  1 
 2 2
3   3
 2 2
  1 

您只需将空间量增加一个字符即可打印钻石的变体:

public class Main {
    public static void main(String[] args) {
        int n = 3;
        for (int i = 1 - n; i < n; i++) {
            int x = Math.abs(i);
            System.out.println("  ".repeat(x) + (n - x)
                    + "  ".repeat(Math.abs((n - x) * 2 - 3))
                    + ((i == 1 - n || i == n - 1) ? "" : (n - x)));
        }
    }
}

输出:

    1  
  2  2
3      3
  2  2
    1  

答案 3 :(得分:0)

替代解决方案:

public static void main(String[] args) {
  int n = 7;
  for (int i = -n; i <= n; i++) {
    for (int j = -n; j <= n; j++) {
      // edge of the diamond
      int edge = Math.abs(i) + Math.abs(j);
      // diamond shape with numbers
      if (edge == n) System.out.print(n - Math.abs(i) + 1);
      // beyond the edge && in chessboard order || vertical borders
      else if (edge > n && (i + j) % 2 != 0 || Math.abs(j) == n)
        System.out.print("*");
      // empty part
      else System.out.print(" ");
    }
    System.out.println();
  }
}

输出:

** * * 1 * * **
* * * 2 2 * * *
** * 3   3 * **
* * 4     4 * *
** 5       5 **
* 6         6 *
*7           7*
8             8
*7           7*
* 6         6 *
** 5       5 **
* * 4     4 * *
** * 3   3 * **
* * * 2 2 * * *
** * * 1 * * **

另见:How to print a given diamond pattern in Java?

答案 4 :(得分:0)

可能有点晚了,但是因为您的消息的底部只是镜像的第一部分,所以您可以使用 Stack 以相反的顺序打印消息:

    public static void main(String[] args) {

        int maxNumber = 3;

        Stack<String> message = new Stack<>();
        
        // upper part
        for(int row = 0; row < maxNumber; row++) {

            int prefix = maxNumber - (row + 1);
            int spaces = row >= 2 ? row * 2 - 1 : row;

            String line = getLine(row, prefix, spaces);
            System.out.println(line);

            if(row != maxNumber - 1)
                message.add(line);
        }
        
        // bottom part
        while(!message.isEmpty())
            System.out.println(message.pop());
    }

    public static String getLine(int row, int prefix, int spaces) {

        StringBuilder line = new StringBuilder("_".repeat(prefix));
        line.append(row+1);

        if(row != 0) {
            line.append("_".repeat(spaces));
            line.append(row+1);
        }

        return line.toString();
    }

输出:

__1
_2_2
3___3
_2_2
__1

您当然可以使用任何您想要填充堆栈的方法(即生成消息的上部),就像这个问题建议的方法一样。我描述的上半部分包含第一行(包含)到中间行(不包含)。

答案 5 :(得分:0)

解决方案:名为 EmptyDiamond.java 的 Java 程序包含一个方法,该方法接受一个整数 n 并在 2n − 1 行上打印一个空菱形。

public class EmptyDiamond {
    public static void main(String[] args) {
        shape(3); // Change n to increase size of diamond
    }

    public static void shape(int n) {
        int max = 2 * n - 1; // length of the diamond - top to bottom
        int loop = 0; // with of each loop. initialized with 0
        for (int i = 1; i <= max; i++) {
            int val = 0;
            if (i <= n) {
                loop = n + i - 1;// e.g. when i = 2 and n = 3 loop 4 times
                val = i; // value to be printed in each loop ascending
            } else {
                loop = n + (max - i); //e.g. when i = 4 and n = 3 loop 4 times
                val = max - i + 1; // value to be printed in each loop descending
            }
            for (int j = 1; j <= loop; j++) {
                // (value end of loop)
                // || (value in the beginning  when i <= n)
                // || (value in the beginning  when i > n)
                if (j == loop
                        || j == (n - i + 1)
                        || j == (n - val + 1)) {
                    System.out.print(val); // Print values
                } else {
                    System.out.print(" "); // Print space
                }
            }
            System.out.println(); // Print next line
        }
    }
}

n = 3时输出:

  1
 2 2
3   3
 2 2
  1

答案 6 :(得分:0)

仅流功能:

public static void printEmptyDiamond(int n) {
   IntStream.range(1, 2*n)
        .map(i-> i > n ? 2*n-i : i)
        .mapToObj(i -> " ".repeat(n-i) + i + (i>1 ? " ".repeat(2*(i-1)-1)+i : ""))
        .forEach(System.out::println);
}

示例输出 (printEmptyDiamond(7)):

      1
     2 2
    3   3
   4     4
  5       5
 6         6
7           7
 6         6
  5       5
   4     4
    3   3
     2 2
      1

附说明:

public static void printEmptyDiamond(int n) {
   IntStream.range(1, 2*n)
        .map(i-> i > n? 2*n-i : i) // numbers from 1 to n ascending, then descending to 1 again
        .mapToObj(i -> " ".repeat(n-i) // leading spaces
            + i // leading number
            + (i>1 ? // only when number is > 1
                " ".repeat(2*(i-1)-1) // middle spaces
                 + i // trailing number
            : ""))
        .forEach (System.out::println);
}

答案 7 :(得分:0)

我这样做是为了好玩,这是代码:

import java.util.Scanner;

public class Diamond {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        int num = read.nextInt();
        read.nextLine();
        //TOP
        for(int i = 1;i<=num;i++) {
            //LEFT
            for(int k = i; k<num;k++) {
                if ( k % 2 == 0 ) {
                    System.out.print(" ");
                }
            else {
                System.out.print(" ");
            }
        }
        if(i>1) {
            for(int j =1;j<=i;j++) {
                if (j==1 || j== i) {
                    for(int u=0;u<j;u++) {
                        System.out.print(" ");
                    }
                    System.out.print(i);
                    
                }
                else {
                    System.out.print(" ");
                }
            }
            System.out.println("");
        }
        else {
            System.out.println("  "+i);
        }
    }
    //BOTTOM
    for(int i = num-1;i>0;i--) {
        for(int k = i; k<num;k++) {
            if ( k % 2 == 0 ) {
                System.out.print(" ");
            }
            else {
                System.out.print(" ");
            }
        }
        if(i>1) {
            for(int j =1;j<=i;j++) {
                if (j==1 || j== i) {
                    for(int u=0;u<j;u++) {
                        System.out.print(" ");
                    }
                    System.out.print(i);
                }
                else {
                    System.out.print(" ");
                }
            }
            System.out.println("");
        }
        else {
            System.out.println(" "+i);
        }
    }
}
}

和输出:

    7
        1
      2  2
     3    3
    4      4
   5        5
  6          6
 7            7
  6          6
   5        5
    4      4
     3    3
      2  2
       1

看过其他答案后,我可以跳过一大堆循环。只是决定在最后振作起来并尽快完成。