简体   繁体   English

在控制台上用 Java 打印金字塔

[英]Printing pyramid in Java on the console

How can I print a pyramid in Java like this我怎样才能像这样在Java中打印金字塔

1
23
456
78910

My current code looks like this:我当前的代码如下所示:

public class T {
    public static void main(String[] args) {
        int i, j, num = 1;
        int n = Integer.parseInt(args[0]);

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

If I try this removing declared i & j then it shows an array out of bounds exception However 'i' & 'j' are creating the problem.如果我尝试删除声明的ij ,那么它会显示一个数组越界异常但是 'i' 和 'j' 正在造成问题。 What should my code look like.我的代码应该是什么样子。

    int val=1;
    for(int i=0;i<6;i++){
        for(int j=1;j<i;j++){
             System.out.print(val);
            val++;
        }
        System.out.print("\n");
    }

initially val is equal to 1 .最初 val 等于 1 。 Inside the first for loop i=0 and j with increase from 1, but when i=0 second for loop doesn't run.在第一个for循环中 i=0 和 j 从 1 开始增加,但是当 i=0 时,第二个 for 循环不运行。 then you get the first value as 1. Then it will point to new line.然后你得到第一个值为 1。然后它将指向新行。

When i=1,j still 1 so second for loop runs 1 time and print 2, because val has increment(val++).当 i=1,j 仍然为 1 时,第二个for循环运行 1 次并打印 2,因为 val 具有增量(val++)。 when j=2 in inside for loop it is not running only print the new value (3) of val there.当 j=2 在内部for循环中它没有运行时,只打印 val 的新值(3)。

so on this will work所以这会起作用

public static void main(String[] args) {
    int num = 1;
    //i is how many numbers per row
    for(int i = 1; i < 5; i++){
        //prints i numbers because j increases from 0 to i, incrementing num each time
        for(int j = 0; j < i; j++){
            System.out.print(num++);
        }
        System.out.println();
    }
}

This code will work for your purposes.此代码将适用于您的目的。

Now, please read on if you would like to understand Java better and see why the compiler was throwing errors in your code.现在,如果您想更好地理解 Java,请继续阅读,看看为什么编译器会在您的代码中抛出错误。 You shouldn't use stackoverflow to copy in paste someone else's code without understanding it.您不应该使用 stackoverflow 在不理解的情况下复制粘贴其他人的代码。 In your code, you were declaring i and j twice.在您的代码中,您声明了ij两次。 In Java, you cannot declare a variable twice.在 Java 中,您不能两次声明一个变量。 You did it first in int i,j, num = 1;你首先在int i,j, num = 1; and then again in each for loop for (int i = 1; i <= lines; i++) .然后在每个 for 循环中再次for (int i = 1; i <= lines; i++) You could correct this by saying for(i = 1; i <= lines; i++) .你可以通过说for(i = 1; i <= lines; i++)来纠正这个问题。 Notice how the int is left out in the second version of the for loop.注意intfor循环的第二个版本中是如何被省略的。 You can simply assign a value to a variable in a for loop rather than creating a new variable as you do when declare the type int i = 1您可以简单地在 for 循环中为变量赋值,而不是像声明类型int i = 1时那样创建新变量

The syntax of a for loop is: for 循环的语法是:

for(initialization; Boolean_expression; update)

{
   //Statements
}

The initialization step is executed first, and only once.首先执行初始化步骤,并且只执行一次。 This step allows you to declare and initialize any loop control variables.此步骤允许您声明和初始化任何循环控制变量。 You are not required to put a statement here, as long as a semicolon appears.只要出现分号,您就不需要在此处声明。

As for the array out of bounds error that you receive, you are trying to read in a command line argument in the statement int n = Integer.parseInt(args[0]);至于您收到的数组越界错误,您正在尝试读取语句int n = Integer.parseInt(args[0]); Notice how the main method has a parameter String[] args .请注意 main 方法如何具有参数String[] args These are called command line arguments and can be passed in if you manually run the program from the command line.这些称为命令行参数,如果您从命令行手动运行程序,则可以传入。 You were trying to read in args[0] which is outside of the bounds of args[] .您试图读取超出 args[] 范围的 args[ args[0] args[]

In other words, if you run换句话说,如果你运行

java MyProgram one two

Then args contains:然后 args 包含:

[ "one", "two" ] [ “一二” ]

public static void main(String [] args) {
   String one = args[0]; //=="one"
   String two = args[1]; //=="two"
}

I suppose you give the number of lines as your only argument, so the code would be我想你把行数作为你唯一的参数,所以代码是

public static void main(String[] args) 
{
    int lines = Integer.parseInt(args[0]);
    int num = 1;
    for (int i = 1; i <= lines; i++) {
        for (int j = 1; j <= i; j++) {
            System.out.print(num);
            num++;
        }
        System.out.println("");
    }
}
int l=1;

for (int i=0; i<5; i++)
  {
     for (int k=0; k<5-i; k++)
     {
        System.out.print(" ");          
     }
     for (int j=0; j<(i*2)+1; j++)
     {
        if(j%2!=0){
            System.out.print(l++);
        }else {
            System.out.print(" ");
        }           
     }
     System.out.println("");
  }
public static void pyramid(int max) {
    int num = 1;
    max = 4;
    for (int row = 0; row < max; row++) {
        for (int column = 0; column < max; column++) 
            System.out.print(column <= row ? num++ : " ");
        System.out.println();
    }     
}
import java.util.Scanner;

/**
 *
 * @author shelc
 */
public class PrintNumberPyramid {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the count : ");
        int number = scanner.nextInt();
        //enter the number of rows you want to print
        pyramid(number);

    }

    public static void pyramid(int rows) {
        int count = 1;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < rows; j++) {
                System.out.print(j <= i ? count++ : " ");
            }
            System.out.println();
        }
    }
}

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

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