如何使用嵌套For循环制作钻石

时间:2013-10-11 02:17:07

标签: java for-loop nested nested-loops

所以我被分配用Java制作带星号的钻石,我真的很难过。这是我到目前为止所提出的:

public class Lab1 
{
   public static void main(String[] args)
   {
      for(int i = 5; i > -5; i--)
      {
         for(int j = 0; j < i; j++)
         {
            System.out.print(" ");
         }
         for(int j = 0; j >= i; j--)
         {
            System.out.print(" ");
         }
         System.out.println("*");
      }
   }
}

***output***

17 个答案:

答案 0 :(得分:3)

为了制作一个钻石,你需要设置空间和星形,我已经使用嵌套循环制作了这个简单的程序,因为我是初学者。

public class Diamond {
    public static void main(String[] args) {
        int size = 9,odd = 1, nos = size/2; // nos =number of spaces
        for (int i = 1; i <= size; i++) { // for number of rows i.e n rows
            for (int k = nos; k >= 1; k--) { // for number of spaces i.e
                                                // 3,2,1,0,1,2,3 and so on
                System.out.print(" ");
            }
            for (int j = 1; j <= odd; j++) { // for number of columns i.e
                                                // 1,3,5,7,5,3,1
                System.out.print("*");
            }
            System.out.println();
            if (i < size/2+1) {
                odd += 2; // columns increasing till center row 
                nos -= 1; // spaces decreasing till center row 
            } else {
                odd -= 2; // columns decreasing
                nos += 1; // spaces increasing

            }
        }
    }
}

你可以看到nos需要减少空间数,直到中心行和星数需要增加,但是在中心行之后它是相反的,即空间增加和星数减少

尺寸 可以是任何数字我在这里设置为9所以我将有一个9号星,最多9行和9列...空格数(nos)将是

9/2 = 4.5

但java会将其视为4,因为int不能存储十进制数,而中心行将是

9/2 + 1 = 5.5

将在int中取为5。

所以首先你要制作行... 9行因此

(int i = 1; i&lt; = size; i ++)// size = 9

然后

像我一样打印空间

(int k = nos; k&gt; = 1; k--)// nos size / 2

然后终于明星

(int j = 1; j <= odd; j ++)

一旦行结束......你可以使用if条件调整星号和空格

答案 1 :(得分:3)

    for (int i = 0; i < 5; i++) 
          System.out.println("    *********".substring(i, 5 + 2*i));

    for (int i =5; i>0;i--)
        System.out.println("     **********".substring(i-1,5+(2*i)-3));

答案 2 :(得分:1)

public class Diamond {

//Size of the diamond
private int diagonal;

public Diamond(int diagonal) {
    this.diagonal = diagonal;
}

public void drawDiamond() {
    int n = diagonal;
    for (int i = n / 2; i >= -n / 2; i--) {
        for (int k = 0; k < i; k++) {
            System.out.print(" ");
        }
        for (int j = 1; j <= (n - i * 2) && i >= 0; j++) {
            System.out.print("*");
        }
        for (int k = 1; k <= -i && i < 0; k++) {
            System.out.print(" ");
        }
        for (int j = (n / 2) * 2 + 2 * i; j >= -(n % 2 - 1) && i < 0; j--) {
            System.out.print("*");
        }
        System.out.println();
    }
}

public static void main(String[] args) {
    Diamond a = new Diamond(21);  //You pass diamond size here in the constructor
    a.drawDiamond();
}
}

主要问题是对角线的平价。 如果它甚至你不能正确绘制顶部星号。因此有两种类型的钻石 - 偶数和奇数对角线(顶部有2和1个星号)。

答案 3 :(得分:1)

enter image description here

**Note :- Using Count Global variable we can manage space as well as star increment and decrement**


import java.util.*;
public class ParamidExample
{
    public static void main(String args[])
    {
        System.out.println("Enter a number");
        Scanner sc=new Scanner(System.in);
        int no=sc.nextInt();

        int count=1;
        for(int i=1;i<=2*no-1;i++)
        {
            for(int j=count;j<=no;j++)
            {
                System.out.print("  "); 
            }
            for(int k=1;k<=count*2-1;k++)
            {
                System.out.print("* ");
            }
        if(i<no)
            count++;
        else
            count--;
                System.out.println(""); 
        }
    }
}

答案 4 :(得分:1)

public class MyDiamond
{
   public static void main(String[] args)
   {
      int numRows=151;//Length of the pyramid that we want.151 is just an example
      int midrow = (numRows+1)/2;//midrow is the middle row and has numRows number of *

      int diff=0;
      for(int i=1;i<numRows+1;i++)
      {
         for(int j=1;j<numRows+1;j++)
         {
            if(((midrow-diff)<=j && (j<=midrow+diff)))
            {
               System.out.print("*");
            }else
            {
               System.out.print(" ");
            }

         }
         System.out.println();
         if(i<midrow)
         {
         diff++;
         }else
         {
            diff--;
         }
      }




   }

}

答案 5 :(得分:0)

import java.util.Scanner;


public class Diamond {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in=new Scanner(System.in);
        int input=in.nextInt();
        int min=1;
        for(int i=0;i<input;i++){
            for(int j=input-1;j>i;j--){
                System.out.print(" ");
            }
            for(int k=0;k<min;k++){
                if(k%2==0){
                    System.out.print("*");
                }else{
                    System.out.print(".");
                }

            }
            min+=2;
            System.out.println();
        }
        int z=input+input-3;
        for(int i=1;i<input;i++){
            for(int j=0;j<i;j++){
                System.out.print(" ");
            }
            for(int k=0;k<z;k++){
                if(k%2==0){
                    System.out.print("*");
                }else{
                    System.out.print(".");
                }
            }
            z-=2;
            System.out.println();

        }

    }

}

答案 6 :(得分:0)

import static java.lang.System.out;
import java.util.Scanner;
public class Diamond {

    public static void main(String[] args) {

    Scanner sc=new Scanner(System.in);
    int row=sc.nextInt();
    sc.close();
    Diamond d=new Diamond();
    d.upperDiamond(row);
    d.lowerDiamond(row-2);

    }
    public void upperDiamond(int a){

    for(int i=0;i<a;i++){
        for(int j=a-1;j>i;j--)
            out.print(" ");
        for(int k=0;k<2*i-1;k++)
        out.print("*");
        out.print("\n");
        }
    }
    public void lowerDiamond(int b){

        for(int i=0;i<b;i++){
        for(int j=0;j<=i;j++)
        out.print(" ");
        for(int k=0;k<2*(b-i)-1;k++)
            out.print("*");
        out.print("\n");
        }
    }

}

答案 7 :(得分:0)

这应该有效。您可能只需要大多数方法和printDiamond(_);

    import java.util.Scanner;
public class StarsTry 
{

    public static void main(String[] args) 
    {
        int reader;
        Scanner kBoard = new Scanner(System.in);
        do
        {
            System.out.println("Insert a number of rows: ");

                reader = kBoard.nextInt();
                printDiamond(reader); 


        }while(reader != 0);

    }

    public static void printStars(int n)
    {
        if(n >= 1)
        {
            System.out.print("*");
            printStars(n - 1);
        }
    }

    public static void printTopTriangle(int rows)
    {
        int x = 1;
        for(int j = (rows - 1); j >= 0; j--,x +=2)
        {
            printSpaces(j);
            printStars(x);
            System.out.print("\n");
        }
    }

    public static void printSpaces(int n)
    {
        if(n >= 1)
        {
            System.out.print(" ");
            printSpaces(n - 1);
        }
    }

    public static void printBottomTriangle(int rows, int startSpaces)
    {
        int x = 1 + (2*(rows - 1));
        for(int j = startSpaces; j <= (rows) && x > 0; j++,x -=2)
        {
            printSpaces(j);
            printStars(x);
            System.out.print("\n");
        }
    }
    public static void printBottomTriangle(int rows)
    {
        int x = 1 + (2*(rows - 1));
        for(int j = 0; j <= (rows - 1) && x > 0; j++,x -=2)
        {
            printSpaces(j);
            printStars(x);
            System.out.print("\n");
        }
    }

    public static void printDiamond(int rows)
    {
        printTopTriangle((int)rows/2 + 1);
        printBottomTriangle((int)rows/2, 1);
    }
}

答案 8 :(得分:0)

import java.util.Scanner;

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

    Scanner sc = new Scanner(System.in);

    while (true) {

        System.out.println("Let's Creat Diamonds");
        System.out.println("If number increases Diamonds gets bigger. Please input number lager than 1 : ");

        int user_input = sc.nextInt(); //gets user's input
        System.out.println("");

        int x = user_input;
        int front_space =  -5;

        for (int i = 0; i < 2 * user_input + 1; i++) {
            for (int a = front_space; a < Math.abs(i - user_input); a++) {
                System.out.print("    "); //Change a bit if diamonds are not in good shape
            }

            if (i < user_input + 1) {
                for (int b = 0; b < 2 * i + 1; b++) {
                    System.out.print("*  "); //Change a bit if diamonds are not in good shape
                }

            } else if (i > user_input) {
                for (int c = 0; c < 2 * x - 1; c++) {
                    System.out.print("*  "); //Change a bit if diamonds are not in good shape
                }
                x--;
            }
            System.out.print('\n');
        }

        System.out.println("\nRun Again? 1 = Run,  2 = Exit : ");

        int restart = sc.nextInt();
        System.out.println("");

        if (restart == 2) {
            System.out.println("Exit the Program.");
            System.exit(0);
            sc.close();
        }
    }
  }
}

用while或for循环制作钻石时。 我认为使用'Math.abs'将是最简单的方法。

您可以通过扫描仪输入数字,当输入数字增加时,钻石会变大。

我用Eclipse制作这个程序。 因此,空间将因您的运行环境而异。像另一个IDE,CMD或终端。如果钻石形状不好。只需改变空格。

答案 9 :(得分:0)

我可以看到你想要做的事情,这是一个考虑钻石的非常巧妙的方式。

当我消极时你会遇到j计数器的一些问题..看看如何使用Math.abs()

还尝试在注释的基本步骤中编写一些伪代码以使模式清晰:

 //print 5 spaces + 1 star
 //print 4 spaces + 2 stars
 //print 3 spaces + 3 stars
 //print 2 spaces+ 4 stars
 .
 . 
 .  
 //print 5 spaces + 1 star

然后,字面上用变量(j和i)代替数字。

你现在有一个模特。这通常是编程中最难的部分......正确地使用模型。只有在你对模型的工作原理有所了解时才进入编码。

一旦替换了变量,就可以尝试将整个事物转换为自动循环。

答案 10 :(得分:0)

尝试一下

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

        int n = 50;
        int space = n - 1;

        for(int i = 0; i < n; i++){

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

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

            System.out.println("");
            space--;
        }

        space = 0;

        for(int i = n; i > 0; i--){

            for(int j = 0; j < space; j++){

                System.out.print(" ");
            }

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

            System.out.println("");
            space++;
        }

    }
}

答案 11 :(得分:0)

package com.DiamondPrintingProgram;

import java.util.Scanner;

public class DiamondPrintingProgram {

    public static void main(String[] args) { 
        int num = getInput();
        int middle = (int) num / 2 + 1;
        printOutput(num,middle); 
    }
    public static int getInput() {
        Scanner sc = new Scanner(System.in);
        int num;
        System.out.print("Enter a odd number: ");
        while (true) {
            num = sc.nextInt();
            if (num % 2 != 0) {
                break;
            }
            System.out.print("Please Enter a ODD NUMBER: ");
        }
        return num;
    }
    private static void printOutput(int num, int middle){
        char asterisk = '*';
        for (int j = 0; j < num; j++) {
            for (int i = 1; i <= num; i++) {
                if (j < middle) {
                    if ((i < (middle - j) || i > (middle + j))) {
                        System.out.print(' ');
                    } else {
                        System.out.print(asterisk);
                    }
                } else {
                    if ((i < (j - middle + 2)) || (i > (2 * num - j - middle))) {
                        System.out.print(' ');
                    } else {
                        System.out.print(asterisk);
                    }
                }
            }
            System.out.println();
        }
    }
}

答案 12 :(得分:0)

我在大学里有确切的课堂作业,这也要求我在 3 个 for 循环中完成。

我就是这样做的。

以简单的方式解释,我将钻石分成两部分。

<头>
没有。行数 没有。空格 没有。星星 总共没有。槽数
1 4 1 5
2 3 3 6
3 2 5 7
4 1 7 8
5 0 9 9
6 1 7 8
7 2 5 7
8 3 3 6
9 4 1 5

我想找到号码。插槽和没有。每行空格,然后分配编号。星星真的很容易。

考虑到没有。槽中,第 1 - 5 行和第 6 - 9 行将成为两个独立的组(即 middleLine)。

没有的等式。前半部分的槽数将是 numberOfLines(i.e. i) + (middleLine - 1) 其中 middleLine - 1 当 maxNumberOfLines 为 9 时为 4。

没有的等式。后半部分的插槽数将是 middleLine(即替换 I) + (middleLine - 1)(即同上) - (i - middleLine) 其中 i - middleLine 在 i = 6 时为 -1。

对于空间来说,前半部分是 middleLine - i,后半部分是 i - middleLine,它们完全呈负相关(或关于它们的斜率对称)。

public class printOutDiamondWith3Loops {

public static void main(String[] args) {
    
    int userInput = 9;

    double maxNumberOfLines = userInput;
    // double type is used instead of integer type in order to prevent removal of remainder when a division performed.
    double middleLine = Math.ceil(maxNumberOfLines/2);

    // Print out the diamond.
    for (int i = 1; i <= maxNumberOfLines; i++) { 
    // Determine the number of lines, which is also the maximum number of slots (the line in the middle).
        if (i <= middleLine) { 
        // Separate the whole diamond into two parts(as mentioned above).
            for (int j = 1; j <= i + ((middleLine - 1)); j++) {
            // Determine the no. of slots in each line from line 1 to 5.
                if (j <= middleLine - i) { 
                // Determine the no. of spaces and stars.
                    System.out.print(" ");
                } else {
                    System.out.print("*");
                }
            }
        } else { // i > middleLine
            for (int k = 1; k <= (middleLine + (middleLine - 1)) - (i - middleLine); k++) {
            // Determine the no. of slots in each line from line 6 to 9.
            // For better understanding, I did not simplify the above condition.
            // Noticeably, the first middleLine in above for loop is a replacement of i.
                if (k <= i - middleLine) {
                // Determine the no. of spaces and stars.
                    System.out.print(" ");
                } else {
                    System.out.print("*");
                }
            }
        } 
        System.out.println();   
    }

}

有了这样的框架,做进一步的改变就容易多了,比如让用户输入no。他们想要的线条。

希望这个回答能帮到你。

我可以借给你我工作的更详细版本,虽然不一定需要(上面的解释已经解释了概念):print-Out-Diamond-With-3-Loops-Advanced-Version.java

答案 13 :(得分:0)

您可以按如下方式打印 asterisks (mathematical operators) 的菱形:

int m = 4;
int n = 4;
for (int i = -m; i <= m; i++) {
    for (int j = -n; j <= n; j++) {
        int val = Math.abs(i) + Math.abs(j);
        System.out.print(val > Math.max(m, n) ? " " : "∗");
        if (j < n) {
            System.out.print(" ");
        } else {
            System.out.println();
        }
    }
}

输出:

        ∗        
      ∗ ∗ ∗      
    ∗ ∗ ∗ ∗ ∗    
  ∗ ∗ ∗ ∗ ∗ ∗ ∗  
∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗
  ∗ ∗ ∗ ∗ ∗ ∗ ∗  
    ∗ ∗ ∗ ∗ ∗    
      ∗ ∗ ∗      
        ∗        

答案 14 :(得分:0)

java-11

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

public class Main {
    public static void main(String[] args) {
        final int MID_ROW_NUM = 5;
        for (int i = 1 - MID_ROW_NUM; i < MID_ROW_NUM; i++) {
            System.out.println(" ".repeat(Math.abs(i)) + "*".repeat((MID_ROW_NUM - Math.abs(i)) * 2 - 1));
        }
    }
}

输出:

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

通过改变空间,您还可以打印钻石的变体:

public class Main {
    public static void main(String[] args) {
        final int MID_ROW_NUM = 5;
        for (int i = 1 - MID_ROW_NUM; i < MID_ROW_NUM; i++) {
            System.out.println("  ".repeat(Math.abs(i)) + "* ".repeat((MID_ROW_NUM - Math.abs(i)) * 2 - 1));
        }
    }
}

输出:

        * 
      * * * 
    * * * * * 
  * * * * * * * 
* * * * * * * * * 
  * * * * * * * 
    * * * * * 
      * * * 
        * 

答案 15 :(得分:-1)

package practice;

import java.util.Scanner;

public class Practice {


    public static void main(String[] args) {

    for(int i=0;i<=10;i++)
    {
        if(i<=5)
        {
        for(int k=1;k<=5-i;k++)
        {
            System.out.print(" ");
        }
        for(int j=0;j<=i;j++)
        {
            System.out.print(" *");
        }
        }
        if(i>5)
        {
        for(int k=0;k<=i-6;k++)
        {
            System.out.print(" ");
        }
        for(int j=0;j<=10-i;j++)
        {
            System.out.print(" *");
        }
        }
        System.out.println();
    }
    }

}

答案 16 :(得分:-1)

class Inc_Dec
{
    public static void main(String[] args)
    {
       int le=11;int c=0;int j1=(le/2)+1;int j2=le-j1;
       for(int i=1;i<=le;i++)
       {
           if(c<j1)
           { 
             for(int k=(j1-i);k>0;k--)
             {
              System.out.print(" ");
             }  
             for(int j=1;j<=i;j++)
             {
                  System.out.print("*"+" ");
             }
             c++;
             System.out.println();
           }
           else
           {
               for(int k=(i-j1);k>0;k--)
               {
                   System.out.print(" ");
               }  
               for(int j=(le-i+1);j>0;j--)
               {
                   System.out.print("*"+" ");
               }
               System.out.println();
           }
       }
    }
}