Home  >  Article  >  Java  >  Use java to input a Yang Hui triangle with a specified number of rows

Use java to input a Yang Hui triangle with a specified number of rows

王林
王林forward
2020-08-29 15:56:063053browse

Use java to input a Yang Hui triangle with a specified number of rows

Yang Hui's triangle is arranged by numbers. It can be regarded as a digital table. Its basic characteristic is that the values ​​​​on both sides are 1, and the values ​​​​in other positions are the values ​​​​in the upper left and The sum of the values ​​in the upper right corner. When printing Yang Hui's triangle, you need to use a for loop statement.

(Video tutorial recommendation: java course)

The implementation idea of ​​printing Yang Hui's triangle is: there are spaces in front of each line, and the number of spaces in each line needs to be based on Determined by the total number of rows, this can be summarized by finding rules. The key is the implementation of the value. The value in each row (except the first and last columns) is the sum of the two values ​​in the previous row, so it can be obtained from the previous row.

The implementation steps are as follows:

(1) Create a class named Test28, declare the num() method in the class, and pass in two parameters in the num() method, namely x and y. where x represents the row and y represents the column. The num() method is used to calculate the value of row x and column y. The code is as follows:

Use java to input a Yang Hui triangle with a specified number of rows

#(2) Create a method named calculate, and pass in a parameter of type int in this method, which represents the number of rows to print Yang Hui's triangle. The code is as follows:

Use java to input a Yang Hui triangle with a specified number of rows

(Related tutorial recommendations: java introductory tutorial)

(3) Add code in the main() method , first receive the number of printing lines input by the user on the console, and then pass the number of lines as a parameter to the calculated() method called. The code is as follows:

Use java to input a Yang Hui triangle with a specified number of rows

#(4) Run the code to test, the running results are as follows:

Use java to input a Yang Hui triangle with a specified number of rows

The above is the detailed content of Use java to input a Yang Hui triangle with a specified number of rows. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:biancheng.net. If there is any infringement, please contact admin@php.cn delete