简体   繁体   English

如何使用循环在 Java 中制作数字三角形,数字从右开始

[英]How to make a numbers triangle in Java using loops, numbers starting from right

my project to create a triangle in Java with numbers starting from the right我的项目是在 Java 中创建一个三角形,数字从右边开始

在此处输入图像描述


import java.util.Scanner;
public class Pyramid {

   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);

      // loop
      for (int i=1; i <= 6; i++) {
         // space
         for(int j=1; j <= 6-i; j++)
         System.out.print(" ");

         // numbers
         for(int k= 1; k <= i; k++)
         System.out.print(k);

         // new line
         System.out.println();
      }
   }
}

Well the only thing you have to do is change order like you are first adding space and then number instead add number and then space.那么你唯一需要做的就是改变顺序,就像你首先添加空格然后数字而不是添加数字然后空格一样。 code -代码 -

import java.util.Scanner;
public class Pyramid {
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

      // loop
      for (int i=1; i <= 6; i++) {
          // numbers
         for(int k= 1; k <= i; k++)
         System.out.print(k);
         
         // space
         for(int j=1; j <= 6-i; j++)
         System.out.print(" ");
         
         // new line
         System.out.println();

      }
  }
}

Now we get the result -现在我们得到结果——

金字塔从右到左。

enter image description here import java.util.Scanner;在此处输入图像描述import java.util.Scanner;

public class Pyramid {公共 class 金字塔 {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int lines = scanner.nextInt();
    for (int i = 0; i <= lines; i++) {
        //space
        int spaceNum = lines - i;
        for (int j = 0; j < spaceNum; j++) {
            System.out.print("  ");
        }
        //numbers
        int numbers = lines - spaceNum;
        for (int j = numbers; j > 0; j--) {
            System.out.print(" " + j);
        }
        System.out.println();
    }

}

} }

start k=i then decrement it till k>=1 .开始k=i然后递减它直到k>=1

for(int k= i; k >=1 ; k--)
     System.out.print(k+" ");

output output

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

Here is one way.这是一种方法。 It uses String.repeat() to pad with leading spaces.它使用String.repeat()填充前导空格。

  • outer loop controls the rows.外循环控制行。
  • Then print the leading spaces然后打印前导空格
  • inner loop iterates backwards, printing the value and a space内部循环向后迭代,打印值和空格
  • then print a newline然后打印一个换行符
int rows = 6;
for (int i = 1; i <= rows; i++) {
    System.out.print("  ".repeat(rows-i));
    for (int k = i; k > 0; k--) {
        System.out.print(k+ " ");
    }
    System.out.println();
}

prints印刷

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

If you don't want to use String.repeat() then use a loop.如果您不想使用String.repeat()则使用循环。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM